一道类似于快速排序算法的题目

答案来源于蓝桥杯老师
题目大致要求如下:
要求一个给定的数组中,负数全部在左,0全部在中间,负数全部在右边,蓝桥杯2013年的一道题
具体编码如下:

#include <iostream>
using namespace std;
void three_step_sort(int *x,int len)
{
  int mod=0;
  int left=0;
  int right=len-1;//数组下表从0开始
  while(mod<=right)
  {
	if(x[mod]<0)
		{
		  int temp=x[left];
		  x[left]=x[mod];
		  x[mod]=temp;
		  left++;
		  mod++;
	}
  else if(x[mod]>0)
  {
		int temp=x[right];
		  x[right]=x[mod];
		  x[mod]=temp;
		   right--;
  }
   else
	   {
		 mod++;
	   }
  
  }
}
int main()
{
	int arr[]={25,13,-2,0,16,-5,33,21,0,19,-16,25,-3,0};
     three_step_sort(arr,14);
	 for(int i=0;i<14;i++)
	 {
	 cout<<arr[i]<<"  ";
	 }
return 0;
}
发布了16 篇原创文章 · 获赞 3 · 访问量 1235

猜你喜欢

转载自blog.csdn.net/delete_bug/article/details/104998678