Computer Science, asked by nooonameee, 11 months ago

GUYZZZ...


??WRITE Bubble sort algorithm in C++??​

Answers

Answered by Anonymous
2

The bubble sort Algorithm simply compares adjacent elements and exchanges them if they are out of order.

To apply the Bubble Sort we follow the following steps.

  • Compare 1st two elements and exchange them if they are out of order.
  • Move down one element and compare 2nd and 3rd elements. Exchange if necessary. Continue until end of array.
  • Pass through array again, repeating process and exchanging as necessary.
  • Repeat until a pass is made with no exchanges.

Online computer science courses to jumpstart your future.

In this lesson we will learn how to write a source code in C++ programming language for doing simple bubble sort using array in ascending order.

______________________________

#include <iostream>

void PrintArray(int *array, int n) {

for (int i = 0; i < n; ++i)

std::cout << array[i] << " " << std::flush;

std::cout << std::endl;

}

void BubbleSort(int *array, int n) {

bool swapped = true;

int j = 0;

int temp;

while (swapped) {

swapped = false;

j++;

for (int i = 0; i < n - j; ++i) {

if (array[i] > array[i + 1]) {

temp = array[i];

array[i] = array[i + 1];

array[i + 1] = temp;

swapped = true;

}

}

}

}

int main() {

int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234};

int n = sizeof(array)/sizeof(array[0]);

std::cout << "Before Bubble Sort :" << std::endl;

PrintArray(array, n);

BubbleSort(array, n);

std::cout << "After Bubble Sort :" << std::endl;

PrintArray(array, n);

return (0);

}

/*

OUTPUT

Before Bubble Sort :

94 42 50 95 333 65 54 456 1 2325

After Bubble Sort :

1 42 50 54 65 94 95 333 456 2325

*/

________________________________

Hope you got it


Anonymous: .. loved to help you.. thanks
nooonameee: ^_^
nooonameee: Actually I'm Grateful to U..
nooonameee: Thanx
Anonymous: Jii????
nooonameee: what??
Anonymous: why were you greatful.???
nooonameee: becoz Tomorrow is my exam
nooonameee: And I was not getting the answer
Similar questions