1、选择排序(升序排列)
#include <iostream>
using namespace std;
void selectionSort(int *array, int len)
{
int min = 0;
for (int i = 0; i < len - 1; ++i)
{
min = i;
for (int j = i + 1; j < len; ++j)
{
if (array[min] > array[j])
{
min = j;
}
}
if (min != i)
{
int tmp = array[min];
array[min] = array[i];
array[i] = tmp;
}
}
}
#if 0
void main()
{
int array[] = { 12, 5, 33, 6, 10 };
int len = sizeof(array) / sizeof(int);
cout << "待排序数组序列:\t\t";
for (int i = 0; i < len; ++i)
{
cout << array[i] << "\t";
}
cout << endl;
selectionSort(array, len);
cout << "选择排序之后的序列:\t";
for (int i = 0; i < len; ++i)
{
printf("%d\t", array[i]);
}
cout << endl;
system("pause");
}
#endif
2、冒泡排序
#include <iostream>
using namespace std;
void bubbleSort(int *array, int len)
{
#if 0
for (int i= 0; i < len; ++i)
{
for (int j = 1; j < len - i; j++)
{
if (array[j] < array[j - 1])
{
int tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
}
}
}
#endif
int flag = 0;
for (int i = len - 1; i > 0 && flag==0; --i)
{
flag = 1;
for (int j = 0; j < i; ++j)
{
if (array[j] > array[j + 1])
{
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
flag = 0;
}
}
}
}
#if 0
void main()
{
int array[] = { 11, 8, 7, 6, 3 };
int len = sizeof(array) / sizeof(int);
cout << "待排序数组序列:\t\t";
for (int i = 0; i < len; ++i)
{
cout << array[i] << "\t";
}
cout << endl;
bubbleSort(array, len);
cout << "冒泡排序之后的序列:\t";
for (int i = 0; i < len; ++i)
{
cout << array[i] << "\t";
}
cout << endl;
system("pause");
}
#endif
3、插入排序
#include <iostream>
using namespace std;
void insertionSort(int *array, int len)
{
int tmp = 0;
int index = 0;
for (int i = 1; i < len; ++i)
{
index = i;
tmp = array[i];
for (int j = i - 1; j >= 0; --j)
{
if (tmp < array[j])
{
array[j + 1] = array[j];
index = j;
}
else
{
break;
}
}
array[index] = tmp;
}
}
#if 0
void main()
{
int i;
int array[] = { 12, 5, 33, 6, 10 };
int len = sizeof(array) / sizeof(int);
cout << "待排序数组序列:\t\t";
for (int i = 0; i < len; ++i)
{
cout << array[i] << "\t";
}
cout << endl;
insertionSort(array, len);
printf("插入排序之后的序列: ");
for (i = 0; i < len; ++i)
{
cout << array[i] << "\t";
}
cout << endl;
system("pause");
}
#endif