Advertisement
Guest User

Untitled

a guest
Sep 1st, 2015
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. typedef int DataType;
  6. const int N_ITEMS = 10;
  7.  
  8. void swap( DataType&, DataType& );
  9. void displayArray( const DataType[], int, int );
  10. void quickSort(DataType[], int, int);
  11. void partition(DataType[], int, int, int&);
  12.  
  13. int main(){
  14. DataType a[ N_ITEMS ] = { 10, 5, 21, 5, 99, 8, 16, 4, 72, 25 };
  15.  
  16. cout << "Initial array : ";
  17. displayArray( a, 0, N_ITEMS - 1 );
  18. cout << endl;
  19.  
  20. quickSort( a, 0, N_ITEMS - 1 );
  21.  
  22. cout << "Sorted array : ";
  23. displayArray( a, 0, N_ITEMS - 1 );
  24. cout << endl;
  25.  
  26. return 0;
  27. }
  28.  
  29. void swap(DataType& x, DataType& y){
  30. DataType temp = x;
  31. x = y;
  32. y = temp;
  33. cout << "Swapped " << setw(2) << x << " with " << setw(2) << y << " --->";
  34. }
  35.  
  36. void displayArray( const DataType theArray[], int first, int last ){
  37. for ( int i = first; i <= last; ++i )
  38. cout << setw(2) << theArray[ i ] << " ";
  39. }
  40.  
  41. void partition(DataType theArray[], int first, int last, int& pivotIndex){
  42. //To do: partition array into [ S1 | Pivot | S2 ]
  43. //set pivot to first element
  44. //sort unknowns to S1 and S2
  45. //given items in S1 are < pivot
  46. // items in S2 are >= pivot
  47. DataType pivot = theArray[first];
  48. cout<<"Pivot="<<pivot<<endl;
  49.  
  50. int lastS1=first;
  51. int firstUnknown = first+1;
  52.  
  53. for (;firstUnknown<=last;firstUnknown++){
  54. if(theArray[firstUnknown]<pivot){
  55. swap(theArray[firstUnknown],theArray[lastS1+1]);
  56. lastS1++;
  57. displayArray(theArray,first,last);cout<<endl;
  58. }
  59.  
  60. }
  61. cout<<"Pivot";swap(theArray[first],theArray[lastS1]);
  62. displayArray(theArray,first,last);cout<<endl;
  63.  
  64. cout<<"After partitioning:";
  65. displayArray(theArray,first,last);cout<<endl<<endl;
  66.  
  67. pivotIndex=lastS1;
  68. }
  69.  
  70. void quickSort(DataType theArray[], int first, int last){
  71. //To do: implement quicksort when items in list > 1
  72. int pivotIndex;
  73. if(first<last)
  74. {
  75. partition(theArray,first,last,pivotIndex);
  76.  
  77. cout<<"Quick sort S1 region:";
  78. displayArray(theArray,first,pivotIndex-1);
  79. cout<<endl;
  80. quickSort(theArray,first,pivotIndex-1);
  81.  
  82. cout<<"Quick sort S2 region:";
  83. displayArray(theArray,pivotIndex+1,last);
  84. cout<<endl;
  85. quickSort(theArray,pivotIndex+1,last);
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement