在c++中对字符串进行排序(冒泡和选择)

Sorting strings in c++ (bubble and selection)

本文关键字:选择 排序 c++ 字符串      更新时间:2023-10-16

这是我对整数进行排序的代码。它包含两个函数,一个是冒泡排序,另一个是选择排序。有没有将它们转换为字符串排序函数的基本方法?谢谢

#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);
}

是的。而且有点简单。也许,您听说过函数strcmp(char*ptr1,char*ptr2)。

它逐字符比较字符串,并返回:

  • 0-如果字符串等于

  • <0第一个不匹配的字符在ptr1中的值低于ptr2 中的值

  • >0第一个不匹配的字符在ptr1中的值大于ptr2 中的值

所以你需要用这个strcmp(array[count],array[count+1])>0替换这个array[count] > array[count + 1]。假设你的数组是char* array[]。否则,它将根本无法正常工作。