1、思路
按位排序,第一位優(yōu)先級大于第二位,第一位相同接著比第二位。照這樣寫完會發(fā)現(xiàn)有一組輸入輸出存在問題。比較321與32,正常的比較得到的結(jié)果是321>32,但是顯然32321>32132。改進(jìn)措施是將輸入數(shù)據(jù)的首位先壓入另一個數(shù)的棧中,即就是比較了323與3213的大小。
1、代碼
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
bool cmp(int a, int b){
stack<int> temp2, temp3;
int aa = a, bb = b;
while(aa > 9) aa = aa / 10;
while(bb > 9) bb = bb / 10;
temp2.push(bb);//放入哨兵
temp3.push(aa);
while(a != 0){
temp2.push(a % 10);
a = a / 10;
}
while(b != 0){
temp3.push(b % 10);
b = b / 10;
}
while(!temp2.empty() && !temp3.empty()){
if(temp2.top() > temp3.top())
return true;
else if(temp2.top() < temp3.top())
return false;
temp2.pop();//這個pop返回void
temp3.pop();
}
return true;//兩個元素相等,隨便將哪一個放到前面
}
int main(){
int n, i;
cin>>n;
int *a = new int[n];
for(i = 0; i < n; ++i)
cin>>a[i];
sort(a, a + n, cmp);
for(i = 0; i < n; ++i)
cout<<a[i];
delete []a;
return 0;
}
3、改進(jìn)
使用string比較