大家好,我是小鸭酱,博客地址为:http://www.cnblogs.com/xiaoyajiang
以下用C++实现插入排序的升序和降序排序
算法来自《算法导论》
#include<iostream>
using namespace std;
void INSERTION_SORT(int *A, int N)
{
for(int j = 1; j < N; ++j)
{
int key = A[j];
int i = j - 1;
while(i >= 0 && key < A[i])
{
A[i + 1] = A[i];
-- i;
}
A[i + 1] = key;
}
}
int main()
{
int b[] = {4,3,2,1};
INSERTION_SORT(b,4);
for(int i = 0; i < 4; ++i)
cout << b[i] << endl;
return 0;
}
----------------------------------------------------------------------------
#include<iostream>
using namespace std;
void INSERTION_DESCSORT(int *A, int N)
{
for(int j = 1; j < N; ++ j)
{
int key = A[j];
int i = j - 1;
while(i >= 0 && A[i] < key)
{
A[i + 1] = A[i];
-- i;
}
A[i + 1] = key;
}
}
int main()
{
int b[] = {1,2,3,4,5};
INSERTION_DESCSORT(b, 5);
for(int i = 0; i < 5; ++i)
cout << b[i] << endl;
return 0;
}