Quicksort

/*******************************************************************************/
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int first, int last) {
    int pivot = arr[last]; // Choose the pivot element (last element)
    int i = first - 1;     // Index of the smaller element

    for (int j = first; j < last; j++) {
        if (arr[j] <= pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }

    swap(&arr[i + 1], &arr[last]); // Place the pivot element in its correct position
    return i + 1;
}

void quickSort(int arr[], int first, int last) {
    if (first < last) {
        int pivotIndex = partition(arr, first, last);

        // Recursively sort the left and right sub-arrays
        quickSort(arr, first, pivotIndex - 1);
        quickSort(arr, pivotIndex + 1, last);
    }
}

int main() {
  int arr[50],n,i;
 
  printf("Enter size of the array: ");
  scanf("%d",&n);
  printf("Enter %d elements: ",n);
  for(i=0;i<n;i++)
    scanf("%d",&arr[i]);

    quickSort(arr, 0, n - 1);

    printf("\nSorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
        }

    return 0;
}

/* Alternate Implementation */

#include<stdio.h>
void quicksort(int [],int,int);
int main(){
int size,i;
printf("Enter size of the array: ");
scanf("%d",&size);

int a[size];

printf("Enter %d elements: ",size);
for(i=0;i<size;i++)
    scanf("%d",&a[i]);

quicksort(a,0,size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",a[i]);

return 0;
}

void quicksort(int a[],int first,int last){
int pivot,j,temp,i;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(a[i]<=a[pivot]&&i<last)
        i++;
while(a[j]>a[pivot])
        j--;

if(i<j){
    temp=a[i];
    a[i]=a[j];
    a[j]=temp;
    }
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}

Comments

Popular posts from this blog

Data Structure Lab CSL 201 Manual KTU - Dr Binu V P-9847390760

Singly Linked List Implementation

Binary search Tree Implementation and Traversal