求一个无序数组的中位数

来源:互联网 发布:淘宝购买充气娃娃图 编辑:程序博客网 时间:2024/06/05 04:28

求一个无序数组的中位数。 如:{2,5,4,9,3,6,8,7,1}的中位数为5。 要求:不能使用排序。

暂时只考虑奇数时的情况,偶数有时会规定相邻两个数的平均数。

下面的分析都只考虑奇数的情况。

思路1:对前(n+1)/2个数据建立大堆存储,然后用堆顶数据与后面数据进行比较,如果堆顶数据比后面数据大,则将堆顶数据与后面数据进行交换。,然后进行一次 向下调整算法,比较结束后,返回堆顶的数据。

实现代码:

void Ajustdown(int* arr, int pos, int size){int parent = pos;int child = parent * 2 + 1;while (child <= size){if (child < size && arr[child] < arr[child + 1])child + 1;if (arr[parent] < arr[child]){swap(arr[parent], arr[child]);parent = child;child = child * 2 + 1;}else{break;}}}void Ajustdown(int *arr, int size){int pos = (size - 2) / 2;while (pos >= 0){Ajustdown(arr, pos, size - 1);pos--;}}void Heap_sort(int*arr, int size){Ajustdown(arr, size);while (size > 1){int temp = arr[0];arr[0] = arr[size - 1];arr[size - 1] = temp;size--;Ajustdown(arr, size);}}int Fid_midnum(int* arr, int start, int end, int size) //求一个无序数组的中位数{int index = (size + 1) / 2;int* str = arr;int i;for (i = 0; i < index; i++){str[i] = arr[i];}Ajustdown(str, index);for (int j = i; j < size; j++){if (str[0] > arr[j]){swap(str[0], arr[j]);}Ajustdown(str, index);}return str[0];}


思路2:利用快排的思想,计算出(n-1)/2 的位置,然后计算出每次快排交换的位置,如果在交换位置的左边那么就进入左边去进行快排,如果在右边则进入右边去快排,如果相等则返回该位置的数据。

实现代码:

int mid(int* arr, int left, int right) //三数取中{int mid = (left + right) / 2;if (arr[left] > arr[mid])swap(arr[left], arr[mid]);if (arr[left] > arr[right])swap(arr[left], arr[right]);if (arr[mid] < arr[right])swap(arr[mid], arr[right]);return right;}int PastSort(int* arr, int start, int end){assert(arr);int left = start;int right = end;int midnum = arr[mid(arr, start, end)];while (left < right){while (left < right && arr[left] <= midnum)left++;if (left < right)arr[right] = arr[left];while (left < right && arr[right] >= midnum)right--;if (left < right)arr[left] = arr[right];}arr[left] = midnum;return left;}int Fid_midnum(int* arr, int start, int end,int size) //求一个无序数组的中位数{int index = (size - 1) / 2;if (start >= end)return 0;int mid = PastSort(arr, start, end);if (mid < index){Fid_midnum(arr, mid + 1, end, size);}else if (mid > index){Fid_midnum(arr, start, mid - 1, size);}else{return arr[index];}}




原创粉丝点击