Ask Question

Write a program in C+ + to implement bubblesort using the swap function?

+3
Answers (1)
  1. 28 June, 02:42
    0
    C+ + program for implementation of Bubble sort

    #include

    using namespace std;

    void swap (int * x, int * y) / *Defining Swap function of void return type*/

    {

    int temp = * x; / /Swaping the values

    *x = * y;

    *y = temp;

    }

    void bubbleSort (int array[], int n) / *Defining function to implement bubbleSort * /

    {

    int i, j;

    for (i = 0; i < n-1; i++)

    for (j = 0; j < n-i-1; j++) / *The last i components are already in location * /

    if (array[j] > array[j+1])

    swap (&array[j], &array[j+1]); / /Calling swap function

    }

    int main () / /driver function

    {

    int array[] = {3, 16, 7, 2, 56, 67, 8}; / /Input array

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

    bubbleSort (array, n); / /Function calling

    cout<<"Sorted array: / n";

    for (int i = 0; i < n; i++) / /printing the sorted array

    cout << array[i] << " ";

    cout << endl;

    return 0;

    }

    Output

    Sorted array:

    2 3 7 8 16 56 67
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a program in C+ + to implement bubblesort using the swap function? ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers