C ++中的冒泡排序算法 [英] Bubble Sorting Algorithm in C++
本文介绍了C ++中的冒泡排序算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对整数数组实施冒泡排序算法,对数组进行排序的函数将数组作为参数,并假定要返回排序后的数组.
I'm trying to implement the bubble sorting algorithm to an array of integers, the function which sorts the array takes an array as a parameter and suppose to return the sorted array.
这是代码:
#include <iostream>
using namespace std;
int* BubbleSort(int data[]){
for(int i=0; i<sizeof(data)/sizeof(data[0])-1; i++){
for(int j=0; j<sizeof(data)/sizeof(data[0])-1-i; j++){
if(data[j+1]>data[j]){
int temp = data[j+1];
data[j+1]=data[j];
data[j]=temp;
}
}
}
return data;
}
int main()
{
int data[]={8,4,9,7,6,5,13,11,10};
int *a=BubbleSort(data);
cout<<"{";
for(int i=0; i<sizeof(data)/sizeof(data[0]); i++){
cout<<a[i];
if(i==sizeof(data)/sizeof(data[0])-1){
cout<<"}"<<endl;
}else{
cout<<",";
}
}
return 0;
}
我得到的输出:{8,4,9,7,6,5,13,11,10}
The output I'm getting: {8,4,9,7,6,5,13,11,10}
推荐答案
您必须传递数组的大小,因为它衰减
的数组指向其第一个元素(元素0)的指针.
You must pass in the size of the array because an array it decays
to the pointer to its first element (element 0).
void BubbleSort(int data[], int size){
for(int i(0); i != size; ++i){
for(int j(i + 1); j != size; ++j){
if(data[i] > data[j]){
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
这篇关于C ++中的冒泡排序算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文