2nd Chapter Sort | | 17th three-color sorting exercises

Source: Internet
Author: User

    • Topic

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]
    • Analytical
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; }};
    • Python
#-*-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.