这是我整理整数的代码。它包含两个函数,一个是冒泡排序,另一个是选择排序。有没有将它们转换为字符串排序函数的基本方法?感谢。
#include <iostream>
#include <string>
using namespace std;
void bubbleSort(int array[], int size){
bool swap;
int temp;
do{
swap = false;
for (int count = 0; count < (size - 1); count++){
if (array[count] > array[count + 1]){
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
}while (swap);
}
void selectionSort(int array[], int size){
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++){
minIndex = startScan;
minValue = array[startScan];
for (int index = startScan + 1; index < size; index++){
if (array[index] < minValue){
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
int main(){
int str[5] = {5, 3, 1, 7, 8};
bubbleSort(str, 5);
selectionSort(str, 5);
}
答案 0 :(得分:0)
是的,确实如此。这很容易。也许,你已经听说过函数strcmp(char * ptr1,char * ptr2)。
它比较字符串char-by-char,并返回:
0 - 如果字符串相等
&lt; 0 第一个不匹配的字符在ptr1中的值低于在ptr2中的值
&gt; 0 不匹配的第一个字符在ptr1中的值大于在ptr2中的值
因此,您需要将此array[count] > array[count + 1]
替换为此strcmp(array[count],array[count+1])>0
。并且它的假设,你的数组是char* array[]
。如果没有,它根本无法正常工作。