-
Notifications
You must be signed in to change notification settings - Fork 522
/
Bubble_sort.cpp
47 lines (39 loc) · 1.24 KB
/
Bubble_sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// A teacher is organizing the scores of students from a recent exam. The students’ scores are initially given in random order. The teacher wants to rank the students from the lowest score to the highest. The teacher decides to use a simple sorting technique, Bubble Sort, to reorder the scores.
// Write a C++ program that reads an array of student scores and sorts them in ascending order using Bubble Sort.
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int scores[] = {78, 92, 88, 65, 70, 95, 60, 85, 80, 90};
int n = sizeof(scores) / sizeof(scores[0]);
cout << "Original scores: ";
for (int i = 0; i < n; i++)
{
cout << scores[i] << " ";
}
cout << endl;
bubbleSort(scores, n);
cout << "Sorted scores in ascending order: ";
for (int i = 0; i < n; i++)
{
cout << scores[i] << " ";
}
cout << endl;
return 0;
}