Implement Bubble Sort using C++

If you’re in a computer science background, widening your technical horizons is the best thing you should do. However, your programming skills matter the most and one must continuously keep sharpening these skills. And to become a better programmer in the future. Though there are multiple things to focus on, one specific area you must focus on is the world of data structures. Data structures in general are specific approaches to solve problems in such a way that computer resources get used minimum. In general, there are multiple data structures you can learn and implement as well. However, to keep things simple were going to start with some basic programs you must learn before moving on to complex algorithms. Therefore today we’re going to learn how to Implement Bubble Sort using C++.

 

What is Bubble Sort?

 

  • Comes in the list of simplest data structures, Bubble Sort is the way of arranging elements in ascending order. The array is either sorted or is unsorted.

 

  • Works by comparing adjacent elements in an array and swapping them, if required. This process continues till each element in an array gets sorted.

 

What’s The Approach?

 

  • Consider array, arr[n] of size n we want to implement Bubble Sort on. So firstly we’ll iterate a for loop, with an iterative variable i from 0 to n-1.

 

  • Next, inside the previous for loop, we’ll iterate a new for loop, with an iterative variable j from 0 to n-i-1.

 

  • we’ll compare the element at iterating index with its next element from the array. If the comparing element is smaller, we’ll swap the elements.

 

Also Read: How To Print Hello World in C++

 

C++ Program To Implement Bubble Sort

 

Input:

 

64, 34, 25, 12, 22, 11, 90

 

Output:

 

Sorted array:

11 12 22 25 34 64 90

 

// C++ program for implementation of Bubble sort

#include <bits/stdc++.h>
using namespace std;

//Function to swap array elements
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

//function to implement bubble sort
void bubbleSort(int arr[], int n)
{
    int i, j;
    for (i = 0; i < n-1; i++)	
    
    // Last i elements are already in place
    for (j = 0; j < n-i-1; j++)
        if (arr[j] > arr[j+1])
            swap(&arr[j], &arr[j+1]);
}

/* Function to print an array */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

// Driver code
int main()
{
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    cout<<"Sorted array: \n";
    printArray(arr, n);
    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *