常見的排序和尋找方法_面試

來源:互聯網
上載者:User

#include<stdio.h>


//直接插入排序


void main()
{
int a[8]={8,7,6,5,4,3,2,1};


int temp;


for (int i=1;i<8;i++)
{
temp=a[i];


int j=i;


if(a[i-1]>temp) //因為是挨個元素插入,所以被插入的序列是已經排序好的序列
{
while(j>0 && a[j-1]>temp)
{
a[j]=a[j-1];


j--;
}


a[j]=temp;
}
}
for( int j=0;j<8;j++)
{
printf("%d ",a[j]);
}


}


-------------------------
#include<stdio.h>


//希爾排序


void ShellSort(int a[],int n)
{
for(int gap=n/2;gap>0;gap /=2)
{
for(int i=0;i<gap;i++)
{
for(int j=i+gap;j<n;j+=gap)//直接插入排序
{
int temp=a[j];


int k=j-gap;


if(a[k]>a[j])
{
while(k>=0 && a[k]>a[j])
{
a[k+gap]=a[k];


k-=gap;
}


a[k+gap]=temp;
}
}
}
}
}


void main()
{
int a[8]={45,78,32,42,41,33,88,22};


ShellSort(a,8);


for(int i=0;i<8;i++)
{
printf("%d ",a[i]);
}
}
-------------------------


#include<stdio.h>


//冒泡排序


void Ball(int a[],int n)
{
int temp;


for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];

a[i]=a[j];


a[j]=temp;
}
}
}
}




void main()
{
int a[9]={3,2,4,6,7,12,32,53,55};


Ball(a,9);

for(int i=0;i<9;i++)
{


printf("%d ",a[i]);
}
}
----------------------
#include<stdio.h>


//快速排序
void FastSeq(int a[],int n)
{
int low=0,high=n-1;


int mid=a[0];


while(low<high)
{


while(a[high]>mid )
{
high--;


//printf("$%d ",high);
}


if(low<high)
{
a[low]=a[high];


low++;
}


while(a[low]<mid)
{
low++;


//printf("#%d ",low);
}


if(low<high)
{
a[high]=a[low];


high--;
}
}


a[low]=mid;


}






void main()


{
int a[8]={49,60,35,77,56,15,36,98};


FastSeq(a,8);


for(int i=0;i<8;i++)
{
printf("%d ",a[i]);
}
}


--------------------------
#include<stdio.h>


//二分尋找
void BinFind(int a[],int K)
{
int low=0,high=7;




while(low<=high)


{
int mid=(low+high)/2;


if(K==a[mid])
{

printf("%d\n ",mid);


break;


}


else if(K>a[mid])
{
low=mid+1;
}


else
high=mid-1;


}


}






void main()


{
int a[8]={1,2,9,12,16,18,52,99};


BinFind(a,9);


for(int i=0;i<8;i++)
{
printf("%d ",a[i]);
}
}











聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.