/*
To sort a given array
{5,7,2,8,9,1,3,4}
*/
Class ArrayTest2
{
/*
Select sort
The inner loop ends once and the maximum value appears in the position of the header
*/
public static void Selectsort (int[] arr)
{
for (int x=0;x<arr.length-1;x++)
{
for (int y=1+x;y<arr.length;y++)
{
if (Arr[x]>arr[y])
{
/*
int temp=arr[x];
Arr[x]=arr[y];
Arr[y]=temp;
*/
Swap (arr,x,y); a sort method already defined in//java, which is used in the development of the sentence code.
}
}
}
}
/*
Bubble sort
*/
public static void Bubblesort (int[] arr)
{
for (int x=0;x<arr.length-1;x++)
{
for (int y=0;y<arr.length-x-1;y++)//-x: To reduce the element for each comparison,-1: Avoid crossing the corner mark.
{
if (arr[y]<arr[y+1])
{
/*
int temp=arr[y];
ARR[Y]=ARR[Y+1];
Arr[y+1]=temp;
*/
Swap (arr,y,y+1);
}
}
}
}
/*
It is found that the elements that satisfy the condition need to be swapped for position regardless of the sort.
So you can extract this part of the same code and encapsulate it individually as a function.
*/
public static void Swap (int[] arr,int a,int b)
{
int Temp=arr[a];
ARR[A]=ARR[B];
Arr[b]=temp;
}
public static void Main (string[] args)
{
Int[] arr={5,7,2,8,9,1,3,4};
Before sorting
PrintArray (arr);
Sort S
Selectsort (arr);
After sorting
Bubblesort (arr);
PrintArray (arr);
}
public static void PrintArray (int[] arr)
{
System.out.print ("[");
for (int x=0;x<arr.length;x++)
{
if (x!=arr.length-1)
System.out.print (arr[x]+ ",");
Else
System.out.println (arr[x]+ "]");
}
}
}
java-implementation of two sorting methods