There is an array of integers consisting only of three elements of 0,1,2, using swap, sort in place instead of counting.
Given an integer array a and its size that contains only 0,1,2, return the sorted array. Ensure that the array size is less than or equal to 500.
Test examples:
[0,1,1,0,2,2],6
return: [0,0,1,1,2,2]
classThreecolor { Public: //The idea has a bugvector<int> Sortthreecolor (vector<int> A,intN) {//Write code here inti =0; while(A[i] = =0) I++; intk = N-1; while(A[k] = =2) K--; intj =i; while(J <k) {if(A[j] = =0) {swap (A[i], a[j]); while(A[i] = =0) I++; } Else if(A[j] = =2) {swap (a[j], a[k]); while(A[k] = =2) K--; } Else{J++; } } returnA; } Vector<int> SortThreeColor2 (vector<int> A,intN) {//Write code here//using the idea of quick-line intleft =-1, right =N; intindex =0; while(index<Right ) { if(a[index]==0) {Swap (a[++Left],a[index]); Index++; }Else if(a[index]==2) {swap (A[index], a[--Right ]); } Else{Index++; } } returnA; }};
#-*-coding:utf-8-*-classthreecolor:def Sortthreecolor (self, A, n): # write code here left=-1 Right=N Index=0 whileindex<Right :ifa[index]==0: Left+=1A[left],a[index]=A[index],a[left] Index+=1elif A[index]==2: Right-=1A[right],a[index]=A[index],a[right]Else: Index+=1 returnA
- 2nd Chapter Sort | | 17th three-color sort exercises: https://www.nowcoder.com/study/vod/1
2nd Chapter Sort | | 17th three-color sorting exercises