三部排序
来源:互联网 发布:卡拉卓华软件 编辑:程序博客网 时间:2024/06/10 01:49
标题:三部排序
一般的排序有许多经典算法,如快速排序、希尔排序等。
但实际应用时,经常会或多或少有一些特殊的要求。我们没必要套用那些经典算法,可以根据实际情况建立更好的解法。
比如,对一个整型数组中的数字进行分类排序:
使得负数都靠左端,正数都靠右端,0在中部。注意问题的特点是:负数区域和正数区域内并不要求有序。
可以利用这个特点通过1次线性扫描就结束战斗!!
可以利用这个特点通过1次线性扫描就结束战斗!!
以下的程序实现了该目标。
其中x指向待排序的整型数组,len是数组的长度。
void sort3p(int* x, int len)
{
int p = 0;
int left = 0;
int right = len-1;
while(p<=right){
if(x[p]<0){
int t = x[left];
x[left] = x[p];
x[p] = t;
left++;
p++;
}
else if(x[p]>0){
int t = x[right];
x[right] = x[p];
x[p] = t;
right--;
}
else{
__________________________; //填空位置
}
}
}
{
int p = 0;
int left = 0;
int right = len-1;
while(p<=right){
if(x[p]<0){
int t = x[left];
x[left] = x[p];
x[p] = t;
left++;
p++;
}
else if(x[p]>0){
int t = x[right];
x[right] = x[p];
x[p] = t;
right--;
}
else{
__________________________; //填空位置
}
}
}
如果给定数组:
25,18,-2,0,16,-5,33,21,0,19,-16,25,-3,0
则排序后为:
-3,-2,-16,-5,0,0,0,21,19,33,25,16,18,25
25,18,-2,0,16,-5,33,21,0,19,-16,25,-3,0
则排序后为:
-3,-2,-16,-5,0,0,0,21,19,33,25,16,18,25
这题在dev上胡乱搞一下就弄出答案来了。
#include <stdio.h> #include <cmath> #include <cstring> #include <string.h> #include <algorithm> #include <iostream>using namespace std;void show();void sort3p(int* x, int len){int p = 0;int left = 0;int right = len-1;while(p<=right){if(x[p]<0){int t = x[left];x[left] = x[p];x[p] = t;left++;p++;}else if(x[p]>0){int t = x[right];x[right] = x[p];x[p] = t;right--;}else{ //填空位置int t = x[left];x[left] = x[p];x[p] = t;p++;}show();}}int a[]={25,18,-2,0,16,-5,33,21,0,19,-16,25,-3,0};void show(){for(int i=0;i<14;++i)printf("%d,",a[i]);printf("\n");}int main(){sort3p(a,14);for(int i=0;i<14;++i)printf("%d,",a[i]);printf("\n");return 0;}
0 0
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序
- 三部排序 - 蓝桥杯
- 标题:三部排序
- 1006-三部排序
- 2013 三部排序
- 标题:三部排序
- 第四届蓝桥杯三部排序
- RPi.GPIO 官方使用文档翻译
- 第一天 POJ 2739
- 贴片钽电容,P型 A型 B型 C型 D型 E型怎么区分?
- 银行家算法
- python发送邮件
- 三部排序
- 蓝桥杯 FJ的字符串
- 链队列的模板类实现
- 类学习一
- 科学界十大伟大算法
- 华为2015机试 最后一题 等式变换
- java异常
- 使用纯CSS3实现一个日食动画
- Windows API with VC6.0sp6Enterprise