2015. 12. 2. 00:39

삽입정렬

#include <iostream>
#define SIZE 10

using namespace std;

int main()
{
    int a[SIZE] = {45,2,46,87,34,12,34,5,9,100};  
    int i;
   
    for(i = 0 ; i < SIZE ; i++)
    {
          int Current = i;// 4
          int Temp = a[i];// 34
          for(; (Current > 0) && (a[Current-1] > Temp) ; Current--){
                 a[Current] = a[Current-1];
                 cout<<"("<<a[Current]<<")"<<endl;
                 }
          a[Current] = Temp;
         
    }
   
    for(int j = 0 ; j < SIZE ; j++)
    {
          cout<<a[j]<<endl;
    }
   
    system("pause");
    return 0;
}

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;  
}

2015. 9. 11. 01:22

버블 정렬 예제 코드

#include <stdio.h>
#define SIZE 10

int main()
{
    int a[SIZE] = {2,52,3,9,6,1,4,32,23,5};
    for(int i = 0 ; i <= SIZE ; i++)
    {
         for(int j = 0 ; j < i ; j++)

         {
        
                 if(a[j] > a[j+1])

                 {
                         int temp;
                         temp = a[j];
                         a[j] = a[j+1];
                         a[j+1] = temp;       
                        
                 }            
         }        
    }
    for(int k = 0 ; k < SIZE ; k++)
    {  
           printf("%d ",a[k]);       
    }
   
    system("pause");
    return 0;
   
}