Write a program for sorting a list of integers in ascending order using the bubb
ID: 3749567 • Letter: W
Question
Write a program for sorting a list of integers in ascending order using the bubble sort algorithm.
Requirements
Implement the following functions:
1. Implement a function called readData
int readData( int *arr)
arr is a pointer for storing the integers. The function returns the number of integers.
The function readData reads the list of integers from a file call data.txt into the array arr. The first integer number in the file is the number of intergers. After the first number, the file lists the integers line by line.
2. void bsort(int *arr, int last)
arr is a pointer to an array of integers to be sorted. last is the number of elements in the array. The function bsort sorts the list of integers in ascending order.
Here is the Link to the Bubble Sort.
3. writeToConsole(int * arr, int last)
arr is a pointer to an array of integers. last is the number of elements in the array. The function writeToConsole displays the sorted list.
4. Do not use the array notation in your solution.
Here is the content of the file data.txt.
9
8
4
7
2
9
5
6
1
3
Explanation / Answer
Answer:
program for sorting a list of integers in ascending order using the bubble sort algorithm:
#include<stdio.h>
int main(){
int array[50], n, i, j, temp;
printf("Enter number of elements ");
scanf("%d", &n);
printf("Enter %d integers ", n);
for(i = 0; i < n; i++)
scanf("%d", &array[i]);
for (i = 0 ; i < ( n - 1 ); i++){
for (j= 0 ; j < n - i - 1; j++){
if(array[j] > array[j+1]){
temp=array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
printf("Sorted list in ascending order: ");
for ( i = 0 ; i < n ; i++ )
printf("%d ", array[i]);
return 0;
}
Output:
Enter number of elements
5
Enter 5 integers
2 3 1 6 4
Sorted list in ascending order:
1
2
3
4
6
(OR)
program for sorting a list of integers in ascending order using the bubble sort algorithm:
Code:
/*
* C program to sort N numbers in ascending order using Bubble sort
* and print both the given and the sorted array
*/
#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num ");
scanf("%d", &num);
printf("Enter the elements one by one ");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is ");
for (i = 0; i < num; i++)
{
printf("%d ", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is... ");
for (i = 0; i < num; i++)
{
printf("%d ", array[i]);
}
}
Output:
Enter the value of num
6
Enter the elements one by one
23
45
67
89
12
34
Input array is
23
45
67
89
12
34
Sorted array is...
12
23
34
45
67
89
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.