bubblesort: stop once list is sorted

This commit is contained in:
Roland W-H 2022-04-26 12:42:14 +01:00
parent a3ea40e9fe
commit e6266f6137
2 changed files with 8 additions and 2 deletions

View File

@ -5,12 +5,16 @@
void bubblesort(int* arr, size_t n)
{
for (int i = 0; i < n; i++)
bool swapped = true;
for (int i = 0; i < n && swapped; i++)
{
for (int elem = 0; elem < n - 1 - i; elem++)
{
swapped = false;
if (arr[elem] > arr[elem + 1])
{
swapped = true;
int temp = arr[elem];
arr[elem] = arr[elem + 1];
arr[elem + 1] = temp;

View File

@ -40,7 +40,8 @@ int main(int argc, char** argv)
"Please pick a mode of operation: "
);
scanf("%s", choice_str);
// Add checking that number is in range
// TODO: Add checking that number is in range
while (!isint(choice_str))
{
printf("Sorry but you must enter a number between 1 and 2\n");
@ -70,6 +71,7 @@ int main(int argc, char** argv)
else if (choice == 2)
{
bubblesort(arr, n);
printf("Here is your sorted list:\n");
for (int i = 0; i < n; i++)
{