冒泡排序:
void bubbleSort(int array[], int count)
{
int flag = 0;
for (int i = 0; i < count - 1 && flag == 0; i++) {
int flag = 1;
for (int j = 0; j < count - i - 1; j++) {
if (array[j] > array[j + 1]) {
swap(array + j, array + j + 1); //交换j和j +1的值
flag = 0;
}
}
}
}
插入排序:
void insertionSort(int array[], int count)
{
for (int i = 1; i < count; i++) {
int j = i;
int temp = array[j];
while (j > 0 && array[j - 1] > temp) {
array[j] = array[j - 1];
j--;
}
array[j] =temp;
}
}
{
for (int i = 1; i < count; i++) {
int j = i;
int temp = array[j];
while (j > 0 && array[j - 1] > temp) {
array[j] = array[j - 1];
j--;
}
array[j] =temp;
}
}
选择排序:
void selectionSort(int array[], int count)
{
for (int i = 0; i < count - 1; i++) {
int minIndex = i;
for (int j = minIndex + 1; j < count; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(array + minIndex, array + i);
}
}
}
{
for (int i = 0; i < count - 1; i++) {
int minIndex = i;
for (int j = minIndex + 1; j < count; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(array + minIndex, array + i);
}
}
}
折半查找:
int halfSeek(const int array[], int count, int target)
{
int start = 0, end = count - 1, mid = 0;
while (start <= end) {
mid = (start + end) / 2;
if (array[mid] > target) {
end = mid - 1;
} else if(array[mid] < target){
start = mid + 1;
} else {
return mid;
}
}
return -1;
}
{
int start = 0, end = count - 1, mid = 0;
while (start <= end) {
mid = (start + end) / 2;
if (array[mid] > target) {
end = mid - 1;
} else if(array[mid] < target){
start = mid + 1;
} else {
return mid;
}
}
return -1;
}
快速排序:
void quickSork(int array[], int count)
{
if(count < 2){
return;
}
int start = 0, end = count - 1;
int temp = array[start];
while (start < end) {
while(start < end && array[end] > temp){
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
if (start < end && array[start] < temp) {
start++;
}
if (start < end) {
array[end] = array[start];
end--;
}
}
array[start] = temp;
quickSork(array, start);
quickSork(array + start + 1, count - start - 1);
}
{
if(count < 2){
return;
}
int start = 0, end = count - 1;
int temp = array[start];
while (start < end) {
while(start < end && array[end] > temp){
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
if (start < end && array[start] < temp) {
start++;
}
if (start < end) {
array[end] = array[start];
end--;
}
}
array[start] = temp;
quickSork(array, start);
quickSork(array + start + 1, count - start - 1);
}