算法的阶梯

Algorithm learning: Quicksort

2018-08-16  本文已影响17人  Tedisaname

There are many kinds of sorting methods when the computer manipulates data.So today I bring one of them, it called quicksort. I write the codes based on C.

Algorithm thoughts: This is the link of quicksort ,you can take this for reference.
quicksort

codes1:

#include <stdio.h>
int a[101];//define the global variable,it will be used at the subfuctions

//this is the quicksort fuction
void quicksort(int left,int right)
{

int i,j,t,temp;//the variable of temp is used to storage the 'guard'
if(left > right)
return;

temp = a[left];
i = left;
j = right;

while(i != j)
{ //the sequence is vital,so need to search from the right to the left
 while(a[j] >= temp && i < j)
{
   j--;
}

//from the left to the right
while(a[i] <= temp && i < j)
{
    i++;
}

//exchange the position of the two numbers in the array
if(i < j)//execute this when the guard i and j haven't encountered together
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}

//finally, return the guard to the position

a[left] = a[i];
a[i] = temp;

quicksort(left,i-1);//go on doing the left part,this is a recursion
quicksort(i+1,right);//go on doing the right part
}

int main()
{ int n,i;    //input the data you need

scanf("%d",&n);

for(i = 1;i <= n;i++)
scanf("%d",&a[i]) ;

quicksort(1,n);//call the quicksort

//print out the result of being sequent
for(i = 1; i <= n;i++)
{
printf("%d ",a[i]);
}

return 0;
}

This is another way to realize it.Just given the codes.

codes 2:

#include <stdio.h>

void print(int * ,int);
void QuickSort(int * ,int,int);
int FindPos(int*,int low,int high);

int main()
{
    int a[6] = {2,5,9,3,5,4};
    QuickSort(a,0,5);
    print(a,6);
    return 0;
} 

void print(int * a,int len)
{
    int i;
    for(i = 0; i < len;i++)
    {
        printf("%d ",a[i]);
    }
}
void QuickSort(int * a,int low,int high)
{
    int pos; 
    if(low < high)
    {
        pos = FindPos(a,low,high);
        QuickSort(a,low,pos-1);
        QuickSort(a,pos+1,high);        
    }
}
//the FindPos function is used to find the position the right position for the gurad
int FindPos(int* a,int low,int high)
{
    int val = a[low];
    while(low < high)
    {
        while(low < high && a[high] >= val)//the condition of moving variable 
            --high;
            a[low] = a[high];
            
        while(low < high && a[low] <= val)//from the left side to move 
            ++low;
            a[high] = a[low];
            
            a[low] = val;//the position of the guard has already been found ,
            //give the value of the position with the value of the gurad    
    }

    return low;//return the coordinate of the guard
}

You can leave me a message if you find out anything incorrect in my diary, I'll correct it, thanks.

上一篇下一篇

猜你喜欢

热点阅读