C 程序使用归并排序对数组进行排序
数组是一组共享同一名称的相关数据项。数组中特定值可以用其“索引号”进行标识。
声明数组
声明数组的语法如下 −
datatype array_name [size];
例如,
float marks [50]
它声明‘marks’为包含50个浮点数元素的数组。
int number[10]
它声明 ‘number’ 为包含最多10个整型常数的数组。
每个元素使用“数组索引”进行标识。
通过使用数组索引可以轻松访问数组元素。
我们用于归并排序的逻辑如下 −
void MergeSort(int *array, int left, int right){ int middle = (left+right)/2; if(left<right){ //Sorting the left part MergeSort(array, left, middle); //Sorting the right part MergeSort(array, middle + 1, right); // Merge the two parts Merge(array, left, middle, right); } }
合并所有元素的逻辑如下 −
void Merge(int *array, int left, int middle, int right){ int tmp[right - left + 1]; int pos = 0, leftposition = left, rightposition = middle + 1; while (leftposition <= middle && rightposition <= right){ if (array[leftposition] < array[rightposition]){ tmp[pos++] = array[leftposition++]; }else{ tmp[pos++] = array[rightposition++]; } } while (leftposition <= middle) tmp[pos++] = array[leftposition++]; while (rightposition <= right) tmp[pos++] = array[rightposition++]; int i; for (i = 0; i < pos; i++){ array[i + left] = tmp[i]; } return; }
程序
下面是C语言归并排序程序 −
#include <stdio.h> void Merge(int * , int , int , int ); void MergeSort(int *array, int left, int right){ int middle = (left+right)/2; if(left<right){ //Sorting the left part MergeSort(array, left, middle); //Sorting the right part MergeSort(array, middle + 1, right); // Merge the two parts Merge(array, left, middle, right); } } void Merge(int *array, int left, int middle, int right){ int tmp[right - left + 1]; int pos = 0, leftposition = left, rightposition = middle + 1; while (leftposition <= middle && rightposition <= right){ if (array[leftposition] < array[rightposition]){ tmp[pos++] = array[leftposition++]; } else{ tmp[pos++] = array[rightposition++]; } } while (leftposition <= middle) tmp[pos++] = array[leftposition++]; while (rightposition <= right) tmp[pos++] = array[rightposition++]; int i; for (i = 0; i < pos; i++){ array[i + left] = tmp[i]; } return; } int main(){ int size; printf("
enter size of array:"); scanf("%d", &size); int array[size]; int i, j, k; printf("
enter the elements in an array:"); for (i = 0; i < size; i++){ scanf("%d", &array[i]); } MergeSort(array, 0, size - 1);//calling sort function for (i = 0; i< size; i++){ printf("%d ", array[i]); } printf("
"); return 0; }
输出
当执行上述程序时,产生以下结果 −
enter size of array:10 enter the elements in an array: 2 -10 34 -3 45 67 -89 34 23 67 -89 -10 -3 2 23 34 34 45 67 67
广告