m2skills

qs c

Sep 10th, 2017
949
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.23 KB | None | 0 0
  1. // Program to implement quick sort in c
  2. #include<stdio.h>
  3. #include<conio.h>
  4. #define Max 30
  5.  
  6. void Quick_Sort(int data[],int first,int last);
  7.  
  8. int main()
  9. {
  10.     int data[Max], number_of_elements, index;
  11.  
  12.     printf("\nEnter your the number of elements to be sorted : ");
  13.     scanf("%d", &number_of_elements);
  14.  
  15.     // accepting string as space seperated inputs
  16.     printf("\nEnter the elements:");
  17.     for(index = 0; index < number_of_elements; index++)
  18.     {
  19.         scanf("%d", &data[index]);
  20.     }
  21.  
  22.     // calling the quick sort function with first position as 0 and last position as list size -1
  23.     Quick_Sort(data, 0, number_of_elements-1);
  24.  
  25.     // printing the sorted list
  26.     printf("\nElements after sorting are :");
  27.     for(index = 0; index < number_of_elements; index++)
  28.     {
  29.         printf("%d ", data[index]);
  30.     }
  31. }
  32.  
  33. // recursive function to implement quick sort
  34. void Quick_Sort(int data[],int first,int last)
  35. {
  36.     int pivot, left_mark, right_mark, temp;
  37.    
  38.     // checking if the array has more than one number
  39.     if(first < last)
  40.     {
  41.         pivot = first;
  42.         left_mark = first;
  43.         right_mark = last;
  44.  
  45.         // loop while left marker is less than right marker
  46.         while(left_mark < right_mark)
  47.         {
  48.             // while the data at the left mark is less than pivot keep incrementing the left_mark
  49.             while(data[left_mark] <= data[pivot] && left_mark < right_mark)
  50.                 left_mark++;
  51.  
  52.             // while the data at the right mark is greater than pivot keep decrementing the right_mark
  53.             while(data[right_mark] >= data[pivot] && left_mark <= right_mark)
  54.                 right_mark--;
  55.  
  56.             // swap the elements if right mark is greater than left mark
  57.             if(right_mark > left_mark)
  58.             {
  59.                 temp = data[right_mark];
  60.                 data[right_mark] = data[left_mark];
  61.                 data[left_mark] = temp;
  62.             }
  63.  
  64.             // finally swap the pivot and the right mark element
  65.             temp = data[pivot];
  66.             data[pivot] = data[right_mark];
  67.             data[right_mark] = temp;
  68.         }
  69.  
  70.         // make recursive calls to the function
  71.         Quick_Sort(data, first, right_mark-1);
  72.         Quick_Sort(data, right_mark+1, last);
  73.     }
  74. }
Add Comment
Please, Sign In to add comment