Common Sorting Algorithms - Java Implementation

1. Bubble sort

  Each time the size of two adjacent elements is compared, the order is adjusted. Execute one round (i) from the beginning to the end, and the element with the largest value is ranked last. One element (length - i - 1) is arranged each time a round is executed from the beginning to the end. This means that for an array of n elements, it takes a maximum of n - 1 times to sort the array. code show as below:

 1 public static void bubbleSort(int[] array) {
 2     int length = array.length;
 3     for (int i = 0; i < length - 1; i++) {
 4         for (int j = 0; j < length - i - 1; j++) {
 5             if (array[j] > array[j + 1]) {
 6                 array[j] ^= array[j + 1];
 7                 array[j + 1] ^= array[j];
 8                 array[j] ^= array[j + 1];
 9             }
10         }
 11          
12          System.out.print("Sort times - " + (i+1) + "Times:" );
 13          printArray(array);
 14      }
 15 }

  The way to test is to choose extreme cases (already sorted, but the opposite). Then do n-1 rounds of comparisons. But it is often not so extreme every time, and there will be several rounds of idling when sorting. At this time, a switch can be used to optimize the above bubble sort.

 

2. Quick Sort

3. Selection sort

4. Insertion sort

5. Merge Sort

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325961110&siteId=291194637