在c++中对字符串进行排序(冒泡和选择)
Sorting strings in c++ (bubble and selection)
这是我对整数进行排序的代码。它包含两个函数,一个是冒泡排序,另一个是选择排序。有没有将它们转换为字符串排序函数的基本方法?谢谢
#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[]
。否则,它将根本无法正常工作。
相关文章:
- C++选择排序算法中的逻辑错误
- 高级选择排序 - 在一次迭代中搜索两个元素
- 选择排序C++(已修改)并非适用于所有情况
- C++为什么我的指针选择排序中存在分段错误?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 选择排序时交换函数调用的数量和完成的交换次数是否相同?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 使用选择排序对数组数据结构进行排序,但它不起作用
- c++ 选择排序在特定情况下不起作用
- 修改的选择排序,选择最大的数字,然后交换到最后
- 如何选择排序一些结构
- 选择排序以查找未排序数组中的最大数字
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 给定数组范围的选择排序问题
- 选择排序算法生成无序结果
- 使用C 中的一系列字符串的选择排序
- 从递归向后选择排序函数调用 max 和交换函数
- 为 STL 列表编写选择排序
- 跟踪选择排序中的交换和比较次数
- 字母选择排序程序的问题