Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Wednesday 27 March 2019

QuickSort Algorithm

ALGORITHM Quicksort(A[l..r])

//Sorts a subarray by quicksort
//Input: Subarray of array A[0..n 1]defined by its left and right
// indices
and r

//Output: Subarray A[l..r] sorted in nondecreasing order

if l < r

Partition(A[l..r]//is a split position

Quicksort(A[l..s 1])

Quicksort(A[1..r]) 

ALGORITHM Partition(A[l..r])

//Partitions a subarray by Hoare’s algorithm, using the first element
// as a pivot


//Input: Subarray of array
A[0..n 1]defined by its left and right
// indices
and r (l < r)
//Output: Partition of A[l..r], with the split position returned as
// this function’s value

← A[l]
← l;

← 1
repeat
repeat ← until A[i≥ p
repeat ← until A[j≤ p
swap(A[i], A[j])
until ≥ j
swap(A[i], A[j]//undo last swap when ≥ j
swap(A[l], A[j])
return j

C program:

#include<stdio.h>
void quicksort(int number[25],int first,int last){
   int i, j, pivot, temp;

   if(first<last){
      pivot=first;
      i=first;
      j=last;

      while(i<j){
         while(number[i]<=number[pivot]&&i<last)
            i++;
         while(number[j]>number[pivot])
            j--;
         if(i<j){
            temp=number[i];
            number[i]=number[j];
            number[j]=temp;
         }
      }

      temp=number[pivot];
      number[pivot]=number[j];
      number[j]=temp;
      quicksort(number,first,j-1);
      quicksort(number,j+1,last);

   }
}

int main(){
   int i, count, number[25];

   printf("How many elements are u going to enter: ");
   scanf("%d",&count);

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

   quicksort(number,0,count-1);

   printf("Order of Sorted elements: ");
   for(i=0;i<count;i++)
      printf(" %d",number[i]);

   return 0;
}

Output:
How many elements are u going to enter: 5
Enter 5 elements: 2
3
1
8
4
Order of Sorted elements:  1 2 3 4 8

0 comments:

Post a Comment