数组的归并排序(不使用辅助空间,循环)

//data[begin,mid)和data[mid,end)两部分交换位置  
void RingShift(int* data, int begin, int mid, int end);

void MergeSort(int* data, int length)
{
	if(data == NULL || length <= 0) return;

	//steps为步长,将data[]分组,每组steps个,然后两两merge
	//steps < length能保证最后肯定被分成两组
	for(int steps = 1; steps < length; steps *= 2)
	{
		//假设merge的两个分组为[left_min,right_min),[right_min,right_max)
		int left_min, right_min, right_max;
		int temp;
		//length - left_min为还没有merge的元素个数,它们应该至少能分两组,才继续进行么merge
		for(left_min = 0; steps < length - left_min; left_min = right_max)
		{
			right_min = left_min + steps;
			right_max = right_min + steps;
			if(right_max > length) right_max = length;

			//merge
			while(left_min < right_min && right_min < right_max)
			{
				while(left_min < right_min && data[left_min] <= data[right_min])
					left_min++;
				if(left_min == right_min) break;

				temp = right_min;
				while(right_min < right_max && data[right_min] < data[left_min])
					right_min++;

				RingShift(data, left_min, temp, right_min);

				left_min += right_min - temp;
			}
		}
	}
}

void swap(int& a, int& b)  
{  
    int temp = a;  
    a = b;  
    b = temp;  
}  
  
//反转data[first,last]  
void reverse(int* data, int first, int last)  
{  
    if(data == NULL) return;  
    while(first < last)  
        swap(data[first++], data[last--]);  
}  
  
//data[begin,mid)和data[mid,end)两部分交换位置  
void RingShift(int* data, int begin, int mid, int end)  
{  
    if(data == NULL) return;  
    reverse(data,begin,mid-1);  
    reverse(data,mid,end-1);  
    reverse(data,begin,end-1);  
} 

你可能感兴趣的:(数据结构与算法)