冒泡
void maopao(int *a, int len)
{
for(int i = 0; i < len - 1; i++)
{
for(int j = 0; j < len - i - 1; j++)
{
if(a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
选择
void xuanzhe(int *a, int len)
{
for(int i = 0; i < len; i++)
{
int k = i;
for(int j = i + 1; j < len; j++)
{
if(a[k] > a[j])
{
k = j;
}
}
if(k != i)
{
int temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
插入
void charu(int *a, int len)
{
for(int i = 1; i < len; i++)
{
int k = i - 1;
int temp = a[i];
while (k >= 0 && a[k] > temp)
{
a[k + 1] = a[k];
k--;
}
a[k + 1] = temp;
}
}
希尔
void xier(int *a, int len)
{
for(int i = len / 2; i >= 1; i /= 2)
{
for(int j = i; j < len; j++)
{
int k = j - i;
int temp = a[j];
while (k >= 0 && a[k] > temp)
{
a[k + i] = a[k];
k-=i;
}
a[k + i] = temp;
}
}
}
快速
int findPos(int *a, int left, int right)
{
if(left < right)
{
int temp = a[left];
while (left < right)
{
while (left < right && a[right] >= temp) {
right--;
}
a[left] = a[right];
while (left < right && a[left] <= temp) {
left++;
}
a[right] = a[left];
}
a[left] = temp;
}
return left;
}
void kuaisu(int *a, int left, int right)
{
if(left < right)
{
int pos = findPos(a,left,right);
kuaisu(a, left, pos - 1);
kuaisu(a, pos + 1, right);
}
}
//-----------------main-----------------
int main(int argc, const char * argv[]) {
int a[] = {9,8,4,8,2,1,0,7,5,9,6,3};
int i = sizeof(a) / sizeof(int);
kuaisu(a, 0, i - 1);
return 0;
}
网友评论