按升序对数字字符串的向量进行排序
给定一个数字字符串向量arr[] ,任务是按升序对给定的数字字符串向量进行排序。
例子:
Input: arr[] = {“120000”, “2”, “33”}
Output: {“2”, “33”, “120000”}
Input: arr[] = {“120”, “2”, “3”}
Output: {“2”, “3”, “120”}
方法: C++ STL 中的 sort()函数能够对字符串向量进行排序当且仅当它包含单个数字字符,例如 { '1', ' '} 但对具有多个字符的字符串的数字向量进行排序,例如, {'12', '56', '14' } 应该编写自己的比较器 在 sort()函数内部。按升序逻辑排序的比较器函数如下:
Let’s build a comparator function considering the two cases given below:
- Case 1: If the length of the string is not the same then place a smaller length string in first place for example, {’12’, ‘2’} place ‘2’ before ’12’ as ‘2’ is smaller than ’12’.
- Case 2: If length is the same then place the string which is numerically smaller for example, ‘1’, ‘2’ place ‘1’ before ‘2’.
下面是实现上述方法的 C++ 程序:
C++
// C++ program for the above approach
#include
using namespace std;
// Comparator Function
bool myCmp(string s1, string s2)
{
// If size of numeric strings
// are same the put lowest value
// first
if (s1.size() == s2.size()) {
return s1 < s2;
}
// If size is not same put the
// numeric string with less
// number of digits first
else {
return s1.size() < s2.size();
}
}
// Driver Code
int main()
{
vector v
= { "12", "2", "10", "6", "4", "99", "12" };
// Calling sort function with
// custom comparator
sort(v.begin(), v.end(), myCmp);
// Print the vector values after
// sorting
for (auto it : v) {
cout << it << " ";
}
cout << "\n";
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Comparator Function
static List sort(List list)
{
Comparator cmp = (o1, o2) -> {
// If size of numeric Strings
// are same the put lowest value
// first
if (o1.length() == o2.length()) {
return Integer.valueOf(o1)-Integer.valueOf(o2);
}
// If size is not same put the
// numeric String with less
// number of digits first
else {
return o1.length()-o2.length();
}
};
Collections.sort(list, cmp);
return list;
}
// Driver Code
public static void main(String[] args)
{
List v
= Arrays.asList( "12", "2", "10", "6", "4", "99", "12" );
// Calling sort function with
// custom comparator
v = sort(v);
// Print the vector values after
// sorting
for (String it : v) {
System.out.print(it+ " ");
}
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 Program to implement
# the above approach
# Comparator Function
from functools import cmp_to_key
def myCmp(s1, s2):
# If size of numeric strings
# are same the put lowest value
# first
if (len(s1) == len(s2)):
return int(s1) - int(s2)
# If size is not same put the
# numeric string with less
# number of digits first
else:
return len(s1) - len(s2)
# Driver Code
v = ["12", "2", "10", "6", "4", "99", "12"]
# Calling sort function with
# custom comparator
v.sort(key = cmp_to_key(myCmp))
# Print the vector values after
# sorting
for i in range(len(v)) :
print(v[i],end=" ")
# This code is contributed by shinjanpatra
Javascript
输出:
2 4 6 10 12 12 99
时间复杂度: O(N*log N)
辅助空间: O(1)