java-implementation of two sorting methods

Source: Internet
Author: User

/*
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.