ที่นี่เราจะดูวิธาสร้างตัวเลขที่ใหญ่ที่สุดโดยการจัดเรียงตัวเลขที่กำหนด สมมติมี {45, 74, 23} โปรแกรมจะหาตัวเลขใหญ่สุดคือ 744523 หมายเหตุ: ไม่ได้จัดเรียงตัวเลขแต่ละหลัก แต่จัดเรียงตัวเลขทั้งจำนวน
วิธีแก้: ใช้การจัดเรียงสตริง (string sorting) แต่ตรรกะการเปรียบเทียบแตกต่าง ฟังก์ชันเปรียบเทียบรับ a และ b ต่อกันเป็น ab และ ba เปรียบเทียบว่าตัวไหนใหญ่กว่า
อัลกอริทึม
compareStrings(a, b)
begin
ab := concatenate b with a
ba := concatenate a with b
compare ba with ab, then return 1 if ba is bigger, otherwise return 0
end
getLargest(arr):
begin
sort the arr with the comparison logic using compareString()
for each string s in arr, do
print s
done
end
ตัวอย่างโค้ด (C++)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int stringCompare(string a, string b) {
string ab = a + b;
string ba = b + a;
return ab.compare(ba) > 0 ? 1 : 0;
}
void getLargest(vector arr) {
sort(arr.begin(), arr.end(), stringCompare);
for (int i = 0; i < arr.size(); i++)
cout << arr[i];
}
int main() {
vector arr;
arr.push_back("45");
arr.push_back("74");
arr.push_back("23");
getLargest(arr);
}
ผลลัพธ์
744523