1. Bubble sort
Algorithm complexity O(n^2)
At the end of each bubbling put the maximum value at the end.
public void BubbleSort(int[] arr) { for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) Swap(arr, j, j + 1); } } }
2. Selection sort
Algorithm complexity O(n^2)
Find the index of the minimum value each time you sort, and then swap to put the minimum value in the front, unlike bubble sort, only swap once after the inner loop is completed,
public void SelectSort(int[] arr) { int minIndex; for (int i = 0; i < arr.Length; i++) { minIndex = i; for (int j = i + 1; j < arr.Length; j++) { if (arr[j] < arr[minIndex]) minIndex = j; } Swap(arr, i, minIndex); } }
3. Insertion sort
Algorithm complexity O(n^2)
Think that the first element is ordered, and then insert the following elements into the correct position in the order
public void InsertSort(int[] arr) { for (int i = 1; i < arr.Length; i++) { int temp = arr[i]; int j = i - 1; while (j >= 0 && temp < arr[j]) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } }