2015. 12. 2. 00:37

quick sort

#include <iostream>

using namespace std;

void quicksort(int arr[],int first,int last);
int partition(int arr[], int first, int last);

int main()
{

quick sort.cpp

 

quick sort.exe


    int array[8] = {216,4,22,8,21,225,2000,237};
    quicksort(array,0,7);
   
  
   
    system("pause");
    return 0;
   
}


void quicksort(int arr[], int first, int last)
{
    int p;
    if(first < last){      
             p = partition(arr,first,last);
             quicksort(arr,first,p-1);
             quicksort(arr,p+1,last);   
    }
     for(int i = 0 ; i < 8 ; i++)
    {
            cout<<arr[i]<<" ";      
    }
    cout<<endl;
}


int partition(int arr[], int first, int last)
{
    int low = first;
    int high = last - 1;
    int temp;
   
    while(low <= high)
    {
              while(arr[last] > arr[low]) low++;
              while(arr[last] < arr[high]) high--;
                 
              // 마지막 피벗과 바꿀 위치가 파악 되었을 떄는 이 부분이 실행되면 안된다.
              if(low <= high){
              temp = arr[low];
              arr[low] = arr[high];
              arr[high] = temp;
              }         
    }
    temp = arr[low];
    arr[low] = arr[last];
    arr[last] = temp;
   
    return low;  
}