RUN

Bubble Sort

Written By -

Bubble Sort

It is also a simple sorting algorithm. It repeatedly compares two items at a time and swapping them in ascending or descending order. The process keeps repeating itself until there are no more swaps needed.

Bubble sort has a complexity of O(n²), where n is number of items being sorted, so we should avoid using bubble sort when n is large.

Swfung8 / CC BY-SA

# Algorithm

//bubble sort

void sort(Student st[], int n)

{

  student temp;

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

  {

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

    {

      if (st[j].Marks < st[j + 1].Marks)

      {

        temp = st[j];

        st[j] = st[j + 1];

        st[j + 1] = temp;

      }

    }

  }

}

Code:

//Program for bubble sort

#include <iostream>
#include<string>
using namespace std;

void bubble(int a[], int N);

int mark[20];

char name[20][20];

int main(void)

{

  int i, j, n, temp;

  char c[20];

  clrscr();

  putchar(‘\n’);

  cout << ”enter number of students\ n”;

  cin >> n;

  cout << ”enter marks and name of students\ n’;

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

  {

    cout << ”enter marks”;

    cin >> marks[i];

    cout << ”enter name”;

    gets(name[i]);

  }

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

    for (j = 0; j < n; j++)

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

  {

    temp = marks[j];

    mark[j + 1] = mark[j];

    mark[j] = temp;

    strcpy(c, name[j]);

    strcpy(name[j + 1], name[j]);

    strcpy(name[j], c);

  }

  cout << ”sorted list\ n”;

  cout << setw(10) << ”Marks” << setw(15) << ”Name” << endl;

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

  {

    cout << setw(10) << mark[i] << setw(15) << name[i] << endl;

  }

  return 0;

}

Report Error/ Suggestion

Related Posts:





CopyRight © 2020

CopyRight © 2020