排序

来源:互联网 发布:未来软件园mac 编辑:程序博客网 时间:2024/05/23 02:05

将由1,2,3组成的乱序序列数排序,使得排序后的顺序为1,2,3.

核心思想:使用begin,end,current三个指针,初始时begin,current指向序列首部,end指向序列尾部。当current指向1时,current++;当current指向0时,current与begin指针的内容交换,current++,begin++;当current指向2时,current与end的内容交换,end--;

// ConsoleApplication52.cpp : 定义控制台应用程序的入口点。//非零元素相对位置不变#include "stdafx.h"#include<iostream>#include<string>using namespace std;//void partition(int *a, int p, int r){//int i, j;//i = r + 1;//for (j = r; j >= 0; j--){//if (a[j] != 0){//i--;//a[i] = a[j];//a[j] = 0;//}//}////cout << i<<endl;//j = i - 1;//for (int k = i ; k <= r; k++){////if (a[k] == 1){//j++;//int temp = a[j];//a[j] = a[k];//a[k] = temp;////}//}////}void SSort(int *a,int n){int *current, *begin, *end;begin = current = a;end = begin + (n-1);while (current <= end){if (*current == 1){current++;}else if (*current == 0){int temp = *begin;*begin = *current;*current = temp;current++;begin++;}else{int temp = *current;*current = *end;*end = temp;end--;}}}void test(int  *a,int r){SSort(a,  r);for (int i = 0; i < r; i++)cout <<a[i] <<" " ;}int _tmain(int argc, _TCHAR* argv[]){int a[10] = {0,1,2,1,1,2,0,2,1,0};test(a, 10);system("pause");return 0;}


0 0
原创粉丝点击