アルゴリズム-高速並べ替えと集計

1560 ワード

1.快速列
#include <stdio.h>
/*//j 0     arr[right]   .12543->12354*/
//  
int Partition(int array[], int left, int right){
int i,j;
int temp;
j=left-1;
for(i=left;i<=right;i++){
if(array[i]<=array[right]){
j++;
temp=array[j];
array[j]=array[i];
array[i]=temp;
}
}
return j;
}
void QuickSort(int arr[],int left,int right){
int pivot;
if(left<right){
pivot=Partition(arr,left,right);
QuickSort(arr,left,pivot-1);
QuickSort(arr,pivot+1,right);
}
}
void main(){
int test;
int arr[]={2,4,3,1,5};
QuickSort(arr,0,4);
int i;
for (i = 0; i < 5; ++i)
{
printf("%d\t", arr[i]);
}
}
 

2.集計ソート
#include <stdio.h>
//             
//10 9 7 6 2 | 4 3 1 5 0 |.....
//  
void Merge(int arr[],int tempArr[],int low,int mid ,int high){
int i=low,j=mid+1;
int k=low;
while(i<=mid&&j<=high){//        
if(arr[i]<arr[j]){
tempArr[k++]=arr[i++];
}else{
tempArr[k++]=arr[j++];
}
}
while(i<=mid){
tempArr[k++]=arr[i++];
}
while(j<=high){
tempArr[k++]=arr[j++];
}
for(i=low;i<=high;i++){
arr[i++]=tempArr[i++];
}
}
//      
void MergeSort(int arr[],int tempArr[],int low,int high){
int mid;
if(low<high){
mid=(low+high)/2;
MergeSort(arr,tempArr,low,mid);
MergeSort(arr,tempArr,mid+1,high);
Merge(arr,tempArr,low,mid,high);
}
}
int main(){
int a[8] = {50, 10, 20, 30, 70, 40, 80, 60};
    int i, b[8];
    MergeSort(a, b, 0, 7);
    for(i=0; i<8; i++)
        printf("%d ", a[i]);
    printf("
"); return 0; }