java-Array Sorting algorithm

Source: Internet
Author: User

1. Array sorting algorithm-bubble sort algorithm

Function: You can sort the elements in an integer array, as with the Arrays.sort method, the only difference is that the sort method can sort an array of arbitrary types.

Example:

public class P_1 {

public static void Main (String args[]) {
Int[] A = new int[] {5,2,6,7,3,9};
P_1 p = new P_1 ();
P.mysort (a);
P.showarray (a);
}

public void Mysort (int[] a) {
for (int i=1;i<a.length;i++) {//comparison number of times (25)
for (int j=0;j<a.length-1;j++) {//two numbers are compared, the large number is moved backwards.
if (A[j]>a[j+1]) {
int temp = A[j];
A[J] = a[j+1];
A[J+1] = temp;
}
}
}
}

public void Showarray (int[] a) {
for (int i=0;i<a.length;i++) {
System.out.println (A[i]);
}
}
}

2. Direct selection of sorting

Function: The direct selection of the sorting function is the same as the bubble sort, is the order of the array elements, the advantage is that the direct selection of sorting algorithm compared to the number of bubble sorting algorithm less.

Example:

public class P_1 {

public static void Main (String args[]) {
Int[] A = new int[] {5,2,6,7,3,9};
P_1 p = new P_1 ();
P.mysort (a);
P.showarray (a);
}

public void Mysort (int[] a) {
int sum = 0;
int index;
for (int i=1;i<a.length;i++) {//the number of comparisons
index = 0;
for (int j=1;j<=a.length-i;j++) {//starts with the first element of the array, the largest number is moved to the last, and is assigned to A[index].
if (A[j]>a[index]) {
index = j;
}
sum++;
}
int temp = A[a.length-i];
A[a.length-i] = A[index]; Copies the largest number to the last element of the last array.
A[index] = temp;
}
SYSTEM.OUT.PRINTLN ("Frequency" +sum); Compare 15 times in total
}

public void Showarray (int[] a) {
for (int i=0;i<a.length;i++) {
System.out.print (">" +a[i]);
}
}
}

java-Array Sorting algorithm

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.