zoukankan      html  css  js  c++  java
  • 快速排序的一个小坑

    第一版不知为何一直报错,代码如下

    
    int partition(int a[], int low, int high)
    {
    	int key = a[low];
    	while (low < high)
    	{
    		while (a[high] >= key && low<high) high--;
    		a[low] = a[high];
    		while (a[low] <= key && low<high) low++;
    		a[high] = a[low];
    	}
    	printf("%d %d", low, high);
    	printf("
    ");
    	a[low] = key;
    	return low;
    
    }
    
    void quickSort(int a[], int low, int high)
    {
    	if (low == high) return;
    	int pivot = partition(a, low, high);
    	quickSort(a, low, pivot - 1);
    	quickSort(a, pivot + 1, high);
    }
    int main()
    {
    	//int a[] = { 46,87,123,12,9,55,3 };
    	//int a[] = { 1,2,3,4,5,6,7 };
    	int a[] = { 7,6,5,4,3,2,1 };
    	//insertSort(a, 7);
    	// bbleSort(a, 7);
    	// lectSort(a, 7);
    	//mergeSort(a, 0, 6);
    	quickSort(a, 0, 6);
    
    	for (int i = 0; i < 7; i++)
    		printf("%d ", a[i]);
    	while (1);
    	return 0;
    }
    
    

    后来发现,当low==pivot时,下面这句话会有问题:

    	quickSort(a, low, pivot - 1);
    

    于是改为:

        if (pivot > low)
    		quickSort(a, low, pivot - 1);
        quickSort(a, pivot + 1, high);
    

    仍然不对,最后发现是下面那句也要改:

    	if (pivot > low)
    		quickSort(a, low, pivot - 1);
    	if(pivot<high)
    		quickSort(a, pivot + 1, high);
    

    但是书上和网上的标答都没有这么麻烦啊??最后发现:我的递归出口是low=hight,而标答是low>=high,如果这样一改,刚才的两句if也就不需要了:

    void quickSort(int a[], int low, int high)
    {
    	if (low >= high) return;
    	int pivot = partition(a, low, high);
    	//if (pivot > low)
    		quickSort(a, low, pivot - 1);
    	//if(pivot<high)
    		quickSort(a, pivot + 1, high);
    }
    
  • 相关阅读:
    简单了解winform
    SqL语句基础之增删改查
    数据库之表
    数据库基本概念与操作
    搞死人不偿命的 Bank系统
    for的循环题
    .net framework 版本汇总
    LinqToEntity模糊查询的方法选择
    日常工作中的点滴:C# 根据字节长度截包含中文的字符串
    64位系统 IIS中应用程序池设置导致 访问数据库错误
  • 原文地址:https://www.cnblogs.com/YuQiao0303/p/9609716.html
Copyright © 2011-2022 走看看