zoukankan      html  css  js  c++  java
  • 归并排序 空间复杂度为O(1)的做法

     #include <iostream>
     #include <cstdlib>
     using namespace std;
     void print(int *arr, int start, int end)
     {
    	for (int i = start; i <= end; ++i)
    		cout << arr[i] << ' ';
    	cout << endl;
     }
     void randData(int *arr, int start, int end)
     {
    	for (int i = start; i <= end; ++i)
    		arr[i] = rand() % 20; 
    	print(arr, start, end);
     }
    
    void merge(int *arr, int start, int mid, int end)
    {
    	int i, j, k, key;
    	i = start;
    	j = mid;
    	while (i < j && j <= end)  //当i等于j或者j到达末尾时终止
    	{
    		if (arr[i] > arr[j])
    		{	
    			k = j;
    			key = arr[j];
    			while (k > i && arr[k - 1] > key)
    			{			
    				arr[k] = arr[k - 1];
    				--k;
    
    			}
    			arr[k] = key;
    			++j;
    		}
    		++i;
    	}
    }
    void mergeSort(int *arr, int start, int end)
     {
    	if(start < end)
    	{
    		int mid = (end + start) / 2;
    		mergeSort(arr, start, mid);
    		mergeSort(arr, mid + 1, end);
    		merge(arr, start, mid + 1,end);
    		print(arr, start, end);
    	}
     }
     /*11 4 2 13 12 2 1 16 18 15*/
     int main()
     {
    	bool bIsContinue = true;
    	char ch = 'n';
    	const int Len = 10;
    	int arr[Len];
    	print(arr, 0, Len - 1);
    
    	while (true == bIsContinue)
    	{
    		randData(arr, 0, Len - 1);
    		mergeSort(arr, 0, Len - 1);
    		cout << "the new array: ";
    		print(arr, 0, Len - 1);
    		cout << "please input yes or no" << endl;
    		cin >> ch;
    		if (ch == 'y' || ch == 'Y')
    			bIsContinue = true;
    		else
    			bIsContinue = false;
    	}
        return 0;
     }
     
     
    
  • 相关阅读:
    Struts的ONGL
    深度解析 Qt 中动态链接库
    QTcpSocket 发送数据的几种方法
    QT GUI总结
    Qt 插件学习(一)
    Qt自定义窗口部件
    Qt事件机制浅析
    VS2008 Qt Designer 中自定义信号槽
    Q窗口操作函数(窗口最大化,全屏,隐藏最大化最小化按钮)
    QT中窗口刷新事件的学习总结
  • 原文地址:https://www.cnblogs.com/yanqi110/p/4913538.html
Copyright © 2011-2022 走看看