1 冒泡排序
int SortBubble(int* array,int size)
{
if (NULL == array ||
0 >= size) {
return 1;
}
for (int count = 1;count < size;count++) {
for (int j = 0;j < size - count;j++) {
if ( array[j] > array[j+1] ) {
int tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
}
}
}
return 0;
}
2 选择排序
int SortSelect(int* array, int size)
{
if (NULL == array ||
0 >= size) {
return 1;
}
for (int count = 1;count < size;count++) {
int key = array[count - 1];
for (int j = count;j < size;j++) {
if ( array[j] < key) {
int tmp = key;
array[count - 1] = array[j];
key = array[count - 1];
array[j] = tmp;
}
}
}
return 0;
}
3 插入排序
int SortInsert(int* array, int size)
{
if (NULL == array ||
0 >= size) {
return 1;
}
//Consider the first element is sorted,then start from the second element to insert.
int start = 0;
for(int i = start + 1;i < size;i++)
{
int cur = array[i];
int j = i - 1;
//Compare the current element to insert with the sorted elements which start from the last element of current element.
while((j >= start) &&
(array[j] > cur)) {
array[j+1] = array[j];
j--;
}
array[j+1] = cur;
}
return 0;
}
4 快速排序
int SortQuick(int* array, int size)
{
if (NULL == array) {
return 1;
}
if (2 > size) return 1;
int start = 0;
int end = size - 1;
int key = array[start];
while (start < end) { //Divide the unsorted part into smaller and bigger parts based on key value until start = end
while (start < end) {
if (array[end] < key) {
array[start] = array[end]; //After this statement, array[end] is empty. The element with bigger index than end must be bigger than key.
start++;//The unsorted area is from start++ to end now.
break;
}
end--;
}
//If code can reach here, then either array[end] is empty or start=end.
//If array[end] is empty, then sort the area from start to end based on key.
while(start < end) {
if (array[start] > key) {
array[end] = array[start];
end--;//The unsorted area is from start to end-- now.
break;
}
start++;
}
}
//start must be EQUAL to end and array[start] is empty now,then assign the key value to it.
array[start] = key;
SortQuick(array, start);
SortQuick(array+start+1, size - start - 1);
return 0;
}
排序算法
最新推荐文章于 2024-11-02 00:39:09 发布