#include #include void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void selection_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int mn = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[mn]) mn = j; swap(&arr[i], &arr[mn]); } } void insertion_sort(int arr[], int n) { for (int i = 0; i < n; i++) { int j = i - 1, x = arr[i]; while (j >= 0 && arr[j] > x) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = x; } } void bubble(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int swapped = 0; for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(&arr[j], &arr[j + 1]); swapped = 1; } } if (!swapped) { break; } } } void merge_sort_helper(int arr[], int b, int m, int e) { int i = 0, j = 0, k = b; int l1 = m - b + 1, l2 = e - m; int l[l1], r[l2]; for (int x = 0; x < l1; x++) l[x] = arr[b + x]; for (int x = 0; x < l2; x++) r[x] = arr[m + 1 + x]; while (i < l1 && j < l2) { if (l[i] <= r[j]) arr[k++] = l[i++]; else arr[k++] = r[j++]; } while (i < l1) arr[k++] = l[i++]; while (j < l2) arr[k++] = r[j++]; } void merge_sort(int arr[], int b, int e) { if (b >= e) return; int m = b + (e - b) / 2; merge_sort(arr, b, m); merge_sort(arr, m + 1, e); merge_sort_helper(arr, b, m, e); } int quick_sort_helper(int arr[], int b, int e) { int p = arr[e]; int i = b - 1; for (int j = b; j < e; j++) { if (arr[j] < p) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[e]); return i + 1; } void quick_sort(int arr[], int b, int e) { if (b < e) { int p = quick_sort_helper(arr, b, e); quick_sort(arr, b, p - 1); quick_sort(arr, p + 1, e); } } void heap_sort_helper(int arr[], int n, int i) { int left = 2 * i + 1; int right = 2 * i + 2; int largest = i; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { swap(&arr[i], &arr[largest]); heap_sort_helper(arr, n, largest); } } void heap_sort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heap_sort_helper(arr, n, i); for (int i = n - 1; i >= 0; i--) { swap(&arr[0], &arr[i]); heap_sort_helper(arr, i, 0); } } void display(int arr[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); } int main() { const int SIZE = 5; int arr1[] = {65, 65, 65, 1, 1}; printf("Insertion Sort on: "); display(arr1, SIZE); insertion_sort(arr1, SIZE); display(arr1, SIZE); int arr2[] = {-4, 91, 300, 912, 8}; printf("Selection Sort on: "); display(arr2, SIZE); selection_sort(arr2, SIZE); display(arr2, SIZE); int arr3[] = {11, -2, 0, 0, -3}; printf("Merge Sort on: "); display(arr3, SIZE); merge_sort(arr3, 0, SIZE - 1); display(arr3, SIZE); int arr4[] = {99999, 9999, 999, 99, 9}; printf("Quick Sort on: "); display(arr4, SIZE); quick_sort(arr4, 0, SIZE - 1); display(arr4, SIZE); int arr5[] = {-9, -99, -999, -9999, -99999}; printf("Heap Sort on: "); display(arr5, SIZE); heap_sort(arr5, SIZE); display(arr5, SIZE); return 0; }