Data Structure Programs using C Language (Unit-3)
Data Structure Programs using C Language (Unit-3)
1. Quick Sort
#include <stdio.h>
// Function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partition function to place pivot element at the correct position
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choose the last element as pivot
int i = low - 1; // Index of smaller element
2. Insertion Sort
#include <stdio.h>
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n); // Call Insertion Sort
printf("Sorted array: ");
printArray(arr, n); // Print sorted array
return 0;
}
OUTPUT:-
3. Selection Sort
#include <stdio.h>
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n); // Call Selection Sort
printf("Sorted array: ");
printArray(arr, n); // Print sorted array
return 0;
}
OUTPUT:-
4. Merge Sort
#include <stdio.h>
int i = 0, j = 0, k = l;
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1); // Call Merge Sort
printf("Sorted array: ");
printArray(arr, n); // Print sorted array
return 0;
}
OUTPUT:-
5. Bubble Sort
#include <stdio.h>
OUTPUT:-
6. Heap Sort
#include <stdio.h>
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n); // Call Heap Sort
printf("Sorted array: ");
printArray(arr, n); // Print sorted array
return 0;
}
OUTPUT:-
7. Radix Sort
#include <stdio.h>
// Do counting sort for every digit. The exp is 10^i where i is the current digit number
for (int exp = 1; max / exp > 0; exp *= 10)
countingSort(arr, n, exp);
}
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
radixSort(arr, n); // Call Radix Sort
printf("Sorted array: ");
printArray(arr, n); // Print sorted array
return 0;
}
OUTPUT:-