In: Computer Science
1. Bubble Sort
Implement a bubble sort program that will read from a file
“pp2.txt” from the current directory a list of intergers (10
numbers to be exact), and the sort them, and print them to the
screen. You can use redirection to read data from a given file
through standard input, as opposed to reading the data from the
file with the read API (similar to Lab #1). You can assume the
input data will only have 10 numbers in the file, and that the
numbers will be valid integers. You must implement 3 functions,
including main(), bubblesort(), and swap(). The function
declarations are included, and they must be followed exactly to
receive full points. All your code should be contained in the
bubblesort.c file, and the Makefile.
Usage:./sort
For example, if you type:
./sort
INPUT: 1 3 2 8 4 9 8 3 10 14
OUTPUT: 1 2 3 3 4 8 8 9 10 14
Bubblesort.c:
#include <stdio.h>
void bubblesort(int [], int);
void swap(int*,int*);
int main()
{
printf("edit the bubblesort.c file to implement your
bubble sort\n");
return 0;
}
The file that should be read:
pp2.txt:
1 3 2 8 4 9 8 3 10 14
CODE:
#include<stdio.h>
#include<stdlib.h>
//function declaration bubblesort and swap
void bubblesort(int [], int);
void swap(int*,int*);
//main function
int main(){
// declare a file pointer to open file
FILE *file;
int element;
// declare a array of size 10
int arr[10];
int i = 0;
// declare index to hold the index of array
int index=0;
// declare size of array n = 10
int n = 10;
// open the file in read mode
file = fopen("pp2.txt","r");
// check if the file exists or not
// if file does not exists then exit the program
if(file==NULL){
printf("Error! File does not
exists\n");
exit(1);
}
//read a line from the file
while (fscanf(file, " %d", &element) == 1) {
// add the element to the array
// increment the index value by 1 to store next
element
arr[index++] = element;
}
//make a call to bubblesort pass array and size as
parameters
bubblesort(arr,n);
//use the for loop to print the array elements after
sorting
for( i =0;i<10;i++){
// print the elements in array
printf("%d ",arr[i]);
}
return 0;
}
//bubble sort function that takes two parameters array and size
of array n
//return the array after sorting
void bubblesort(int arr[],int n){
// declare two variables i and j
int i,j;
// use nested for loops to traverse through the
array
for( i = 0;i<n-1;i++){
for( j=0;j<n-i-1;j++){
// check if the
previous element is greater than next element
// if true then
make a call to swap
if(arr[j]>arr[j+1]){
//
make a call to swap to swap elements
swap(&arr[j],&arr[j+1]);
}
}
}
}
//function that takes two reference parameters
//return the two values after swapping
void swap(int* a,int* b){
//declare the temp variable
int temp;
// store value of a in temp
temp = *a;
// update a value with b
*a = *b;
// update b value with temp
*b = temp;
}