Skip to main content
Search
Search This Blog
Livecodo
Pages
Home
Courses
Blog
About us
More…
Share
Get link
Facebook
X
Pinterest
Email
Other Apps
May 02, 2024
Write a c program to implement Insertion sort & Quick sort
Insertion Sort:
#include
int insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i- 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } int printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); printf("Unsorted array: \n"); printArray(arr, n); insertionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0; }
Quick Sort:
#include
int swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low- 1); for (int j = low; j <= high- 1; j++) { if (arr[j] < pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } int quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi- 1); quickSort(arr, pi + 1, high); } } int printArray(int arr[], int size) { for (int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf("Unsorted array: \n"); printArray(arr, n); quickSort(arr, 0, n- 1); printf("Sorted array: \n"); printArray(arr, n); return 0; }
Popular Posts
March 26, 2024
Dynamic Memory allocation in C
May 18, 2024
Searching and sorting Algorithm in C