Common Sorting Algorithms

selection sort

Idea : First find the smallest element in the array, then swap positions with the first element in the array, and then find the smallest element in the remaining elements and swap positions with the second element in the array. Repeat the above steps until all elements are sorted.

Pseudocode :

class SelectionSort () {
    public static void sort (Caparable[] a) {
	int N = a.length();
	//Start looping through the array
	for (int i = 0; i < N; i++) {
	    //min represents the subscript of the smallest element. At the beginning, it is assumed that the first element is the smallest
	    int min = i;
	    // Loop through the remaining elements and find the smallest element
	    for (int j = i + 1; j < N; j++) {
		if (a[j] < a[min]) {
		    min = j;//The minimum element subscript is assigned to min
		}
		swap(a[i], a[min]);//Swap elements
	    }
	}
    }
}

Complexity analysis : double-layer loop, the complexity is n².


Insertion sort

   

Guess you like

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