This repository has been archived by the owner on Oct 7, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 203
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Prakhar Rathore <114171306+prakhar2347@users.noreply.github.com>
- Loading branch information
1 parent
183f693
commit aeb2843
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
#include <stdio.h> | ||
|
||
// Function to swap two elements in an array | ||
void swap(int* a, int* b) { | ||
int temp = *a; | ||
*a = *b; | ||
*b = temp; | ||
} | ||
|
||
// Function to partition the array and return the pivot index | ||
int partition(int arr[], int low, int high) { | ||
int pivot = arr[low]; // Choose the leftmost element as the pivot | ||
int i = low + 1; // Index of the first element greater than the pivot | ||
|
||
for (int j = low + 1; j <= high; j++) { | ||
// If the current element is smaller than the pivot, swap it with arr[i] | ||
if (arr[j] < pivot) { | ||
swap(&arr[i], &arr[j]); | ||
i++; | ||
} | ||
} | ||
|
||
// Swap the pivot element with arr[i-1], which is its correct position | ||
swap(&arr[low], &arr[i - 1]); | ||
return (i - 1); | ||
} | ||
|
||
// Function to perform quicksort | ||
void quicksort(int arr[], int low, int high) { | ||
if (low < high) { | ||
// Find the pivot index | ||
int pivot_index = partition(arr, low, high); | ||
|
||
// Recursively sort the elements before and after the pivot | ||
quicksort(arr, low, pivot_index - 1); | ||
quicksort(arr, pivot_index + 1, high); | ||
} | ||
} | ||
|
||
int main() { | ||
int arr[] = {12, 11, 13, 5, 6, 7}; | ||
int n = sizeof(arr) / sizeof(arr[0]); | ||
|
||
printf("Original Array: "); | ||
for (int i = 0; i < n; i++) { | ||
printf("%d ", arr[i]); | ||
} | ||
printf("\n"); | ||
|
||
quicksort(arr, 0, n - 1); | ||
|
||
printf("Sorted Array: "); | ||
for (int i = 0; i < n; i++) { | ||
printf("%d ", arr[i]); | ||
} | ||
printf("\n"); | ||
|
||
return 0; | ||
} |