m2skills

qs cpp

Sep 10th, 2017
947
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. // Program to implement quick sort in c++
  2. #include<iostream>
  3. using namespace std;
  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.     cout<<"\nEnter your number of elements to be sorted : ";
  13.     cin>>number_of_elements;
  14.  
  15.     // accepting string as space seperated inputs
  16.     cout<<"\nEnter the elements:";
  17.     for(index = 0;index < number_of_elements ;index++)
  18.     {
  19.         cin>>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.     cout<<"\nElements after sorting are :";
  27.     for(index = 0; index < number_of_elements; index++)
  28.     {
  29.         cout<<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.    
  49.             // while the data at the left mark is less than pivot keep incrementing the left_mark
  50.             while(data[left_mark] <= data[pivot] && left_mark < right_mark)
  51.                 left_mark++;
  52.  
  53.             // while the data at the right mark is greater than pivot keep decrementing the right_mark
  54.             while(data[right_mark] >= data[pivot] && left_mark <= right_mark)
  55.                 right_mark--;
  56.  
  57.             // swap the elements if right mark is greater than left mark
  58.             if(right_mark > left_mark)
  59.             {
  60.                 temp = data[right_mark];
  61.                 data[right_mark] = data[left_mark];
  62.                 data[left_mark] = temp;
  63.             }
  64.  
  65.             // finally swap the pivot and the right mark element
  66.             temp = data[pivot];
  67.             data[pivot] = data[right_mark];
  68.             data[pivot] = temp;
  69.         }
  70.  
  71.         // make recursive calls to the function
  72.         Quick_Sort(data, first, right_mark-1);
  73.         Quick_Sort(data, right_mark+1, last);
  74.     }
  75. }
Add Comment
Please, Sign In to add comment