Summary of 7 commonly used sorting algorithms in Java

Summary of 7 commonly used sorting algorithms in Java

I have been free for a while, so I took some time to summarize the seven commonly used sorting algorithms in Java. I hope I can review them later!

1. Insertion sort algorithm

The basic idea of ​​insertion sort is that in the process of traversing the array, it is assumed that the elements before serial number i, that is, [0..i-1], have been sorted. This trip needs to find the correct position k of the element x corresponding to i, and in the process of finding this position k, move the compared elements back one position one by one to "make room" for the element x, and finally assign the element value corresponding to k to x. In general, the time complexity and space complexity of insertion sort are O(n2) and O(1), respectively.

  1. /**
  2. * @param int[] unsorted array
  3. * @return int[] sorted array
  4. */  
  5.  
  6. public   int [] sortInsert( int [] array){
  7. for ( int i= 1 ;i<array.length;i++){
  8. int temp = array[i];
  9. int j;
  10. for (j=i- 1 ;j >= 0 && temp< array[j]; j--){
  11. array[j + 1 ] = array[j];
  12. }
  13. array[j + 1 ] = temp;
  14. }
  15. return array;
  16. }

2. Selection sort algorithm

The basic idea of ​​selection sort is to traverse the array, with i representing the number that needs to be sorted, and then find the minimum value in the remaining [i…n-1], and then exchange the minimum value found with the value pointed to by i. Because there is a sub-process of selecting the highest value in each process of determining the element, people figuratively call it selection sort. The time complexity and space complexity of selection sort are O(n2) and O(1) respectively.

  1. /**
  2. * @param int[] unsorted array
  3. * @return int[] sorted array
  4. */  
  5.  
  6. public   int [] sortSelect( int [] arr){
  7. for ( int i = 0 ; i < arr.length; i++) {
  8. int miniPost = i;
  9. for ( int m = i + 1 ; m < arr.length; m++) {
  10. if (arr[m] < arr[miniPost]) {
  11. miniPost = m;
  12. }
  13. }
  14.  
  15. if (arr[i] > arr[miniPost]) {
  16. int temp;
  17. temp = arr[i];
  18. arr[i] = arr[miniPost];
  19. arr[miniPost] = temp;
  20. }
  21. }
  22. return arr;
  23. }

3. Bubble sort algorithm

Bubble sort is to put larger numbers at the bottom and smaller numbers at the top.

  1. /**
  2. * @param int[] unsorted array
  3. * @return int[] sorted array
  4. */  
  5.  
  6. public   int [] sortBubble( int [] array){
  7. int temp;
  8. // First level loop: indicates the number of comparisons, for example, if there are length elements, the number of comparisons is length-1 (it is definitely not necessary to compare with itself)  
  9. for ( int i= 0 ;i<array.length- 1 ;i++){
  10. for ( int j = array.length - 1 ; j > i; j--) {
  11. if (array[j] < array[j - 1 ]) {
  12. temp = array[j];
  13. array[j] = array[j - 1 ];
  14. array[j - 1 ] = temp;
  15. }
  16. }
  17. }
  18. return array;
  19. }

4. Quick sort algorithm

Through a sorting process, the records to be sorted are divided into two independent parts. The keywords of one part of the records are smaller than those of the other part. Then, the two parts of the records can be sorted separately to achieve the purpose of ordering the entire sequence. The essence is to find a base position (pivot, watershed, which is smaller than the left and larger than the right. It can be random and named base. First, start from the rightmost side of the sequence to find a smaller one than base. If it is smaller, change the position, so that the base moves to the position on the right just now (smaller than the base when compared) (recorded as a temporary high position), so that the right side of the base is larger than the base. Then, start from the leftmost side of the sequence to find a larger one than base. If it is larger, change the position, so that the base moves to the position on the left just now (larger than the base when compared) (recorded as a temporary low position), so that the left side of the base is smaller than the base. Repeat the above two steps until low == high, which makes the pivot and watershed truly found. Return to this position, and recurse on the sequences on the left and right of the watershed respectively.

  1. /**
  2. * @param int[] unsorted array
  3. * @return int[] sorted array
  4. */  
  5.  
  6. public   int [] sortQuick( int [] array){
  7. return quickSort(array, 0 , array.length- 1 );
  8. }
  9.  
  10. private   int [] quickSort( int [] arr, int low, int high) {
  11. if (low < height) {
  12. int division = partition(arr, low, high);
  13. quickSort(arr, low, division - 1 );
  14. quickSort(arr, division + 1 , high);
  15. }
  16. return arr;
  17. }
  18.  
  19. // Watershed, base, the ones on the left are smaller than this position, the ones on the right are larger  
  20. private   int partition( int [] arr, int low, int high) {
  21. int base = arr[low]; //Use the first record of the subtable as the pivot (watershed) record  
  22. while (low < heigh) { //Scan alternately from both ends of the table to the middle  
  23. while (low < high && arr[heigh] >= base) {
  24. heigh--;
  25. }
  26. // base is assigned to the current heigh position, base is moved (swapped) here, the right side of the heigh position is larger than base  
  27. swap(arr,heigh,low);
  28. while (low < high && arr[low] <= base) {
  29. low++;
  30. }
  31. // When the value on the left is larger than the base value, change the position  
  32. swap(arr,heigh,low);
  33. }
  34. // now low = high;  
  35. return low;
  36. }
  37.  
  38. private   void swap( int [] arr, int a, int b) {
  39. int temp;
  40. temp = arr[a];
  41. arr[a] = arr[b];
  42. arr[b] = temp;
  43. }

5. Merge sort algorithm

Merge sort is implemented recursively, which belongs to the "divide and conquer" method. The target array is divided into two from the middle, and then the two arrays are sorted separately. After the sorting is completed, the two sorted arrays are "merged" together. The most important thing about merge sort is the "merging" process. The merging process requires additional space that is the same length as the two arrays to be merged.

  1. /**
  2. * @param int[] unsorted array
  3. * @return int[] sorted array
  4. */  
  5. private   int [] sort( int [] nums, int low, int high) {
  6. int mid = (low + high) / 2 ;
  7. if (low < high) {
  8. // left  
  9. sort(nums, low, mid);
  10. // Right  
  11. sort(nums, mid + 1 , high);
  12. // Merge left and right  
  13. merge(nums, low, mid, high);
  14. }
  15. return nums;
  16. }
  17.  
  18. private   void merge( int [] nums, int low, int mid, int high) {
  19. int [] temp = new   int [high - low + 1 ];
  20. int i = low; // left pointer  
  21. int j = mid + 1 ; // right pointer  
  22. int k = 0 ;
  23. // Move the smaller numbers to the new array first  
  24. while (i <= mid && j <= high) {
  25. if (nums[i] < nums[j]) {
  26. temp[k++] = nums[i++];
  27. } else {
  28. temp[k++] = nums[j++];
  29. }
  30. }
  31. // Move the remaining numbers on the left into the array  
  32. while (i <= mid) {
  33. temp[k++] = nums[i++];
  34. }
  35. // Move the remaining numbers on the right into the array  
  36. while (j <= high) {
  37. temp[k++] = nums[j++];
  38. }
  39. // Overwrite the nums array with the numbers in the new array  
  40. for ( int k2 = 0 ; k2 < temp.length; k2++) {
  41. nums[k2 + low] = temp[k2];
  42. }
  43. }
  44.  
  45. public   int [] sortMerge( int [] array) {
  46. return sort(array, 0 , array.length - 1 );
  47. }

6. Shell sort algorithm

Shell sort was born because insertion sort encounters the problem of moving too many elements when processing large-scale arrays. The idea of ​​Shell sort is to "divide and conquer" a large array into several small arrays, divided by gap. For example, the array [1, 2, 3, 4, 5, 6, 7, 8], if divided by gap = 2, can be divided into two arrays [1, 3, 5, 7] and [2, 4, 6, 8] (correspondingly, if gap = 3, the divided arrays are: [1, 4, 7], [2, 5, 8], [3, 6]) and then insert sort the divided arrays separately. After each sub-array is sorted, reduce the gap value and repeat the previous steps until gap = 1, that is, insert sort the entire array. At this time, the array is basically sorted, so the elements that need to be moved will be very small, which solves the problem of a large number of moves when inserting sort is processing large arrays.

Shell sort is an improved version of insertion sort. It is very helpful to improve efficiency when the amount of data is large. When the amount of data is small, it is recommended to use insertion sort directly.

  1. /**
  2. * @param int[] unsorted array
  3. * @return int[] sorted array
  4. */  
  5.  
  6. public   int [] sortShell( int [] array) {
  7. // Get the increment  
  8. int step = array.length / 2 ;
  9. while (step >= 1 ) {
  10. for ( int i = step; i < array.length; i++) {
  11. int temp = array[i];
  12. int j = 0 ;
  13. // The difference from insertion sort is here  
  14. for (j = i - step; j >= 0 && temp < array[j]; j -= step) {
  15. array[j + step] = array[j];
  16. }
  17. array[j + step] = temp;
  18. }
  19. step /= 2 ;
  20. }
  21. return array;
  22. }

7. Heap sort algorithm

The essence is to first construct a big top heap, parent is larger than children, the root node is the *** node, swap the *** node (root) with the tail node (the *** node, which is smaller), leaving the *** tail node, now ***, and the rest, starting from the *** element to the position before the tail node, construct a big top heap recursively.

  1. /**
  2. * @param int[] unsorted array
  3. * @return int[] sorted array
  4. */  
  5. public   int [] sortHeap( int [] array) {
  6. buildHeap(array); // Build heap  
  7. int n = array.length;
  8. int i = 0 ;
  9. for (i = n - 1 ; i >= 1 ; i--) {
  10. swap(array, 0 , i);
  11. heapify(array, 0 , i);
  12. }
  13.  
  14. return array;
  15. }
  16.  
  17. private   void buildHeap( int [] array) {
  18. int n = array.length; // Number of elements in the array  
  19. for ( int i = n / 2 - 1 ; i >= 0 ; i--)
  20. heapify(array, i, n);
  21. }
  22.  
  23. private   void heapify( int [] A, int idx, int max) {
  24. int left = 2 * idx + 1 ; // index of left child (if it exists)  
  25. int right = 2 * idx + 2 ; // index of left child (if it exists)  
  26. int largest = 0 ; // Find the index of the node with the largest value among the three nodes  
  27. if (left < max && A[left] > A[idx])
  28. largest = left;
  29. else  
  30. largest = idx;
  31. if (right < max && A[right] > A[largest])
  32. largest = right;
  33. if (largest != idx) {
  34. swap(A, largest, idx);
  35. heapify(A, largest, max);
  36. }
  37. }
  38. }
  39. // Create a heap function, assuming that only s is in [s, m]  
  40. // The corresponding keyword does not meet the definition of a big heap. Make [s, m] a big heap by adjusting ==========================================================  
  41. public   static   void heapAdjust( int [] array, int s, int m) {
  42. // Use the 0 subscript element as the temporary storage unit  
  43. array[ 0 ] = array[s];
  44. // Filter down along the larger child nodes  
  45. for ( int j = 2 * s; j <= m; j *= 2 ) {
  46. // Ensure that j is the subscript of the larger child node, j < m, ensure that j+1 <= m, and do not cross the boundary  
  47. if (j < m && array[j] < array[j + 1 ]) {
  48. j++;
  49. }
  50. if (!(array[ 0 ] < array[j])) {
  51. break ;
  52. }
  53. // If S is smaller, the larger child should be moved up  
  54. array[s] = array[j];
  55. // The value of the larger child becomes the smaller value of the S position, which may cause an imbalance in the top heap, so the heap where it is located is screened  
  56. s = j;
  57. }
  58. // If the S bit is larger, the value remains unchanged; otherwise, the S bit moves down to 2*s, 4*s, . . .  
  59. array[s] = array[ 0 ];

<<:  Starting a business? Actually, I just don’t want to work.

>>:  Mobile, Ecosystems, and the Death of the PC

Recommend

A collection of Father’s Day poster copywriting, Durex is the best! !

For the upcoming Father's Day, many brands wi...

How to operate your Zhihu? Just read this article!

Whether from the perspective of user growth or us...

6 ways to increase user activity!

How to maintain and increase activity and improve...

Guangzhou server rental configuration price list?

Guangzhou server rental configuration price list?...

Why are mobile phones getting more expensive?

I think the reasons can be roughly divided into t...

What should you do when you try hard to fall asleep but can't?

The lives of modern people are becoming increasin...