Sort Colors <LeetCode>

本文介绍了一种利用快速排序算法解决三色排序问题的方法。通过将颜色编码为整数并进行排序,实现不同颜色元素的相邻排列。重点在于实现快速排序函数及其关键部分,包括分区操作和递归调用。

Sort Colors

 

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You are not suppose to use the library's sort function for this problem.

 

思路:该题很简单,直接把快排实现以下,代码如下:

 

 

 1 class Solution {
 2 public:
 3     void sortColors(int A[], int n) {
 4         if(n==1)  return;
 5         quick_sort(A,0,n-1);
 6     }
 7     
 8     void quick_sort(int A[],int l,int r)
 9     {
10         if(l>=r)  return;
11         else
12         {
13            int mid=fen(A,l,r);
14            quick_sort(A,l,mid-1);
15            quick_sort(A,mid+1,r);
16         }
17     }
18     
19     int fen(int A[],int  l,int r)
20     {
21         int k=A[l];
22         int i=l;
23         int j=r;
24         while(i<j)
25         {
26             while(A[i]<=k&&i<j){i++;}
27             while(A[j]>=k&&i<j){j--;}
28            
29             swap(A[i],A[j]);
30         }
31         if(A[l]>A[i])
32         {
33           swap(A[l],A[i]);
34           return i;
35         }
36         else
37         {
38         swap(A[l],A[i-1]);
39            return i-1;
40         }
41     }
42 };

 

转载于:https://www.cnblogs.com/sqxw/p/3953894.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值