0% found this document useful (0 votes)
69 views1 page

Bubble Sort in C++

This document describes how to implement bubble sort in C++ to sort an integer array in ascending order. The bubbleSort function takes the array and size as parameters and has two nested for loops to iterate through the array and swap adjacent elements that are out of order. The main function initializes an integer array, calls bubbleSort to sort it, and printArray to output the sorted array.

Uploaded by

Valore Dutti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views1 page

Bubble Sort in C++

This document describes how to implement bubble sort in C++ to sort an integer array in ascending order. The bubbleSort function takes the array and size as parameters and has two nested for loops to iterate through the array and swap adjacent elements that are out of order. The main function initializes an integer array, calls bubbleSort to sort it, and printArray to output the sorted array.

Uploaded by

Valore Dutti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

// Bubble sort in C++

#include <iostream>
using namespace std;

// perform bubble sort


void bubbleSort(int array[], int size) {

// loop to access each array element


for (int step = 0; step < size; ++step) {

// loop to compare array elements


for (int i = 0; i < size - step; ++i) {

// compare two adjacent elements


// change > to < to sort in descending order
if (array[i] > array[i + 1]) {

// swapping elements if elements


// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
cout << " " << array[i];
}
cout << "\n";
}

int main() {
int data[] = {-2, 45, 0, 11, -9};

// find array's length


int size = sizeof(data) / sizeof(data[0]);

bubbleSort(data, size);

cout << "Sorted Array in Ascending Order:\n";


printArray(data, size);
}

You might also like