极大数
又是数组下标访问越界了
当i或j超过右端点时,又在if判断中被拿来当下标参与比较,然后进入arr数列了
还有一处
左边数列的右端点就是中间的数,不应该用mid + 1
mid的计算
这里mid不能这样计算,否则会出现这样的情况
大量重复数字
本来想在i或j超过原来范围的时候强制把它转为右端点,但这样的话,每次赋值就都赋两个数列中,第一个被遍历完的数列的右端点了
C源码
//this function uses Divid-and-Conquer algorithm to sort unordered array
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 10
void Sort(int*a, int left, int right);//to divide the array into the smallest ordered pieces
void Merge(int*a, int left, int mid, int right);//to merge the ordered two pieces into a larger one
int main()
{
srand((unsigned int)time(0));//initialize the seed
int *a = (int*)malloc(sizeof(int)*N);//to create a test array
int i;
for(i = 0; i < N; i++)
{
a[i] = rand()%200 - 100;//to assign a random number from -100 to 100 to a[i]
}
Sort(a, 0, N - 1);//sort the array
for(i = 0 ; i < N; i++)//print the array
{
printf("%d ", a[i]);
}
return 0;
}
void Sort(int*a, int left, int right)
{
if(left >= right)//if divide the array into the smallest pieces
return;
int mid = left + (right - left)/2;//calculate the mid point
Sort(a, left, mid);//sort the left side
Sort(a, mid + 1, right);//sort the right side
Merge(a, left, mid, right);//merge from bottom to top
}
void Merge(int*a, int left, int mid, int right)
{
int size = right - left + 1;//the size of the array to store the ordered array
int*arr = (int*)malloc(sizeof(int)*size); //allocate space to arr
int i = left, j = mid + 1, k = 0; //i-the index of the left array
//j-the index of the right array
//k-the index of the new array
for(k = 0; k < size; k++)
{
if(i <= mid && j <= right)//if both of the two arrays are not traversed
{
//assign the smaller one to arr earlier, thus the arr is in increasing order
if(a[i] <= a[j])
{
arr[k] = a[i];
i++;
}
else if(a[j] < a[i])
{
arr[k] = a[j];
j++;
}
}
//if one of the array is traversed, just assign the left part of the other array to arr
else if(i > mid && j <= right)
{
arr[k] = a[j++];
}
else if(j > right && i <= mid)
{
arr[k] = a[i++];
}
}
//assign the value of arr one by one to a, which are already in increasing order
for(k = left; k <= right; k++)
{
a[k] = arr[k - left];
}
}