C++中有多种排序数组的方法,以下是其中的一些常见方法: 冒泡排序(BubbleSort):通过比较相邻元素的大小,不断交换位置,将较大值逐渐“冒泡”到数组的最后
C++中有多种排序数组的方法,以下是其中的一些常见方法:
- 冒泡排序(BubbleSort):通过比较相邻元素的大小,不断交换位置,将较大值逐渐“冒泡”到数组的最后。
voidbubbleSort(intarr[],intn){
for(inti=0;i<n-1;i++){
for(intj=0;j<n-i-1;j++){
if(arr[j]>arr[j+1]){
inttemp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
voidselectionSort(intarr[],intn){
for(inti=0;i<n-1;i++){
intminIndex=i;
for(intj=i+1;j<n;j++){
if(arr[j]<arr[minIndex]){
minIndex=j;
}
}
inttemp=arr[i];
arr[i]=arr[minIndex];
arr[minIndex]=temp;
}
}
voidinsertionSort(intarr[],intn){
for(inti=1;i<n;i++){
intkey=arr[i];
intj=i-1;
while(j>=0&&arr[j]>key){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
}
intpartition(intarr[],intlow,inthigh){
intpivot=arr[high];
inti=low-1;
for(intj=low;j<=high-1;j++){
if(arr[j]<pivot){
i++;
inttemp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
inttemp=arr[i+1];
arr[i+1]=arr[high];
arr[high]=temp;
returni+1;
}
voidquickSort(intarr[],intlow,inthigh){
if(low<high){
intpi=partition(arr,low,high);
quickSort(arr,low,pi-1);
quickSort(arr,pi+1,high);
}
}
这些仅仅是一些常见的排序算法,C++中还有其他排序算法的实现。根据实际情况和需求,选择合适的排序算法既能提高排序效率,也能减少资源消耗。
版权声明
本文仅代表作者观点,不代表博信信息网立场。