diff --git a/counting-sort/counting_sort.cpp b/counting-sort/counting_sort.cpp new file mode 100644 index 0000000..a7b3b3d --- /dev/null +++ b/counting-sort/counting_sort.cpp @@ -0,0 +1,49 @@ +#include +#include +using namespace std; +void display(int *array, int size) { + for(int i = 1; i<=size; i++) + cout << array[i] << " "; + cout << endl; +} +int getMax(int array[], int size) { + int max = array[1]; + for(int i = 2; i<=size; i++) { + if(array[i] > max) + max = array[i]; + } + return max; +} +void countSort(int *array, int size) { + int output[size+1]; + int max = getMax(array, size); + int count[max+1]; + for(int i = 0; i<=max; i++) + count[i] = 0; + for(int i = 1; i <=size; i++) + count[array[i]]++; + for(int i = 1; i<=max; i++) + count[i] += count[i-1]; + for(int i = size; i>=1; i--) { + output[count[array[i]]] = array[i]; + count[array[i]] -= 1; + } + for(int i = 1; i<=size; i++) { + array[i] = output[i]; + } +} +int main() { + int n; + cout << "Enter the number of elements: "; + cin >> n; + int arr[n+1]; + cout << "Enter elements:" << endl; + for(int i = 1; i<=n; i++) { + cin >> arr[i]; + } + cout << "Array before Sorting: "; + display(arr, n); + countSort(arr, n); + cout << "Array after Sorting: "; + display(arr, n); +} \ No newline at end of file diff --git a/quick-sort/quick_sort.c b/quick-sort/quick_sort.c new file mode 100644 index 0000000..acecef7 --- /dev/null +++ b/quick-sort/quick_sort.c @@ -0,0 +1,55 @@ + +#include + + +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +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); +} + +void 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); + } +} + +void printArray(int arr[], int size) +{ + int i; + for (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]); + quickSort(arr, 0, n-1); + printf("Sorted array: n"); + printArray(arr, n); + return 0; +} \ No newline at end of file