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.
Here is the code:
#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;
}
The output I'm getting: {8,4,9,7,6,5,13,11,10}
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;
}
}
}
Maybe too late, but maybe in the future it will be useful,
Try to use this code
...
/**
* Sort array of integers with Bubble Sort Algorithm
*
* @param arr Array, which we should sort using this function
* @param arrSZ The size of the array
* @param order In which order array should be sort
*
* @return Sorted array of integers
*/
void bubbleSortInt(double arr[], int arrSz, string order = "ascending")
{
for (int i = 0; i < arrSz; ++i)
{
for (int j = 0; j < (arrSz - i - 1); ++j)
{
// Swapping process
if ((order == "descending") ? arr[j] < arr[j + 1] : arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
return; // Optional because it's a void function
}// end bubbleSortInt
...
Then use it in your main function like below,
...
double integers[array_size];
const int array_size = 10;
string order = "ascending";
bubbleSortInt(integers, array_size, order)
for (int i = 0; i < array_size; ++i)
{
cout << integers[i] << "\t";
}
...
Have a detailed look at the bubble sort algorithm -> https://github.com/teamroyalcoder/algorithms#bubble-sort-algorithm
This is a GitHub repo where you will find a bunch of algorithms with full details and source code written in c++
https://github.com/teamroyalcoder/algorithms
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.