1.Description
Suppose an array A consists
of n elements,
each of which is red, white, or blue. We seek to rearrange the elements so that all the reds come before all the whites, which come before all the blues. Your algorithm should run in O(n) time
in the worst case using O(1) space.
2.Algorithm
Partition the array using Red as pivot. When done, all the red element will be at the beginning of the array.
Partition the remaining array, from the last Red element until the end, using Blue as pivot. Done.
3.Implementation
import java.util.Arrays;
public class HW2 {
public static void rearrange(String a[])
{
int i=0,n=a.length,j=n-1;
while(i<j)
{
while(i<n&&a[i]=="red") i++;
while(j>=0&&a[j]!="red") j--;
if(i<j) swap(a,i,j);
}
j=n-1;
while(i<j)
{
while(i<n&&a[i]=="white") i++;
while(j>=0&&a[j]!="white") j--;
if(i<j) swap(a,i,j);
}
}
//exchange two elements in the array
public static void swap(String a[] ,int i,int j)
{
String temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public static void main(String[] args){
String seq[] = {"blue", "white","red", "blue", "blue", "red", "red", "white", "red","white"};
rearrange(seq);
System.out.println(Arrays.toString(seq));
}
}Screenshot of the result:


本文介绍了一种通过红蓝绿三种颜色标记数组元素位置的快速排序算法实现,该算法能够在O(n)的时间复杂度下完成排序,并且仅使用常数级别的额外空间。
699

被折叠的 条评论
为什么被折叠?



