zoukankan      html  css  js  c++  java
  • 编程算法

    切割排序 代码(C)


    本文地址: http://blog.csdn.net/caroline_wendy


    排序切割, 把一个数组分为, 大于k小于k等于k的三个部分.

    能够使用高速排序的Partition函数, 进行处理, 把大于k的放在左边, 小于k的放在右边.

    使用一个变量记录中间的位置, 则时间复杂度O(3n/2).


    代码:

    /*
     * main.cpp
     *
     *  Created on: 2014.9.18
     *      Author: Spike
     */
    
    /*eclipse cdt, gcc 4.8.1*/
    
    #include <iostream>
    #include <list>
    #include <queue>
    #include <string.h>
    #include <stdlib.h>
    
    using namespace std;
    
    int RandomInRange(int min, int max) {
    	return rand()%(max-min+1) + min;
    }
    
    void Swap(int* num1, int* num2) {
    	int tmp = *num1;
    	*num1 = *num2;
    	*num2 = tmp;
    }
    
    int PartitionK (int data[], int length, int k)
    {
    	if (data == NULL || length <= 0)
    		return -1;
    	int small = -1;
    	int index = 0;
    	for (index=0; index<length; ++index) {
    		if (data[index] < k) {
    			small++;
    			if (small != index)
    				Swap(&data[small], &data[index]);
    		}
    	}
    
    	int pos = ++small; //记录位置
    
    	small = length;
    	index = 0;
    	for (index = length-1; index>=pos; index--) {
    		if (data[index] > k) {
    			small--;
    			if (small != index)
    				Swap(&data[small], &data[index]);
    		}
    	}
    	return --small;
    }
    
    int main (void)
    {
    	int data[] = {1, 3, 2, 5, 2, 0, 5, 2, -1, 0, 4};
    	int length = sizeof(data)/sizeof(data[0]);
    	PartitionK(data, length, 2);
    	for (int i=0; i<length; ++i) {
    		cout << data[i] << " ";
    	}
    	cout << endl;
    	return 0;
    }
    

    输出:

    1 0 -1 0 2 2 2 3 5 5 4 
    






    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    浏览器检测
    EcmaScript基础
    js中的内置对象
    cursor 与refcursor及sys_refcursor的区别 (转载)
    各种连接数据方法的网站
    UVa11627 Slalom
    UVa1450 Airport
    UVa12124 Assemble
    UVa11384 Help is needed for Dexter
    UVa11464 Even Parity
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4687531.html
Copyright © 2011-2022 走看看