Last active
April 8, 2022 01:37
-
-
Save nishidy/773f0919ab638461cba5dbfdaa714a67 to your computer and use it in GitHub Desktop.
Quick sort in C++ with concise debug message (going from both lowest index and highest index toward the middle)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <utility> | |
using namespace std; | |
void ___m1(string* s, int lo, int hi){ | |
cout << "Let's sort! [" << lo << "," << hi << "] "; | |
for(int i=0;i<lo;i++) cout << (*s)[i]; | |
cout << "|"; | |
for(int i=lo;i<=hi;i++) cout << (*s)[i]; | |
cout << "|"; | |
for(int i=hi+1;i<s->size();i++) cout << (*s)[i]; | |
cout << endl; | |
} | |
void ___m2(string* s, int l, int r, string m){ | |
cout << " " << m << " " << l << "," << r << " "; | |
for(int i=0;i<(l<r?l:r);i++) cout << (*s)[i]; | |
cout << "[" << (*s)[(l<r?l:r)] << "]"; | |
if(l==r){ | |
for(int i=l+1;i<s->size();i++) cout << (*s)[i]; | |
}else{ | |
for(int i=(l<r?l:r)+1;i<(l<r?r:l);i++) cout << (*s)[i]; | |
cout << "[" << (*s)[(l<r?r:l)] << "]"; | |
for(int i=(l<r?r:l)+1;i<s->size();i++) cout << (*s)[i]; | |
} | |
cout << endl; | |
} | |
void qs(string* s, int lo, int hi){ | |
___m1(s,lo,hi); | |
int l=lo,r=hi,pi=lo; // pivot is the first one | |
string p=string(1,(*s)[pi]); | |
if(lo<hi){ | |
while(l<r){ | |
while(string(1,(*s)[l])<=p && l<hi) l++; | |
while(p<string(1,(*s)[r]) && lo<r) r--; | |
___m2(s,l,r,"BEFORE"); | |
if(l<r){ | |
swap((*s)[l],(*s)[r]); | |
___m2(s,l,r,"AFTER "); | |
} | |
} | |
___m2(s,pi,r,"BEFORE(p)"); | |
swap((*s)[pi],(*s)[r]); | |
___m2(s,pi,r,"AFTER (p)"); | |
qs(s,lo,r-1); | |
qs(s,r+1,hi); | |
} | |
} | |
int main(){ | |
string s; | |
cin >> s; | |
qs(&s,0,s.size()-1); | |
cout << s << endl; | |
} |
Author
nishidy
commented
Apr 8, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment