Question

*****C++ program***** Please implement the following, comments throughout code to explain, and provide screenshots of output...

*****C++ program***** Please implement the following, comments throughout code to explain, and provide screenshots of output for proof.

Write a program for sorting a list of integers in ascending order using the bubble sort algorithm. 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

Homework Answers

Answer #1

#include<iostream>
#include<fstream>
#include<sstream>
#include<cstdlib>
using namespace std;
//function that reads the number of integers and those integers
//from data.txt and stores in arr passed to it.
//there is a mistake in passing *arr , it only modifies the arr variable
//in function once the function is executed no modifications are done to arr variable
//that's why double pointer is used and in main function address of arr variable of type int * is passed.
//see the main code for readData function call.
int readData(int **arr)
{
   int len = 0;
   //open file
   ifstream inp("data.txt");
   string line;
   int num = 0;
   //get first line from data.txt
   getline(inp,line);
   //pass it to stringstream object
   stringstream s(line);
   //copy the integer type value in stringstream to num
   s >> num;
   //if num is 0, or instead of number sum text is there in data.txt
   //stringsream assigns nothing and 0 will be still there in num var
   //at that time prompt the user and exit.
   if(num == 0)
   {
       cout<<"\nWarning: Number of Integers specified as 0 or not a number in data.txt.\n";
       cout<<"Not reading file\n";
       inp.close();
       return 0;
   }
   //create memory for array of size num(which is first line value in data.txt)
   *arr = new int[num];
   //till file is read completly
   while(getline(inp,line))
   {
       stringstream ss(line);
       //here stringsream is used it will automatically
       //assigns the read string value into passed datatype variable
       //here num variable of type int is passed. so stringstream will convert
       //the string into integer.
       //if it founds other than integer that is stored in it then
       //it will assigns nothing.that's why for every wrong num in file
       //0 is inserted to achieve this after completion of while block statements
       //each time num is set to 0.
      
       ss >> num;
      
       //assign read num into len_th position of array .
       //since arr var is double pointer use * to get the value in it(base address of type int *arr passed).
       *((*arr)+len) = num;
       //increment length
       len++;
       //increment position
       //num is set to 0 , to achieve invalid number in file are set to 0.
       num = 0;
   }
   inp.close();
   //return the length
   return len;
}
//function that prints the array contents
void writeToConsole(int *arr,int last)
{
   cout<<"\n------- Array Elements --------\n\n";
   //from start element to last element print the array elements
   for(int i =0;i<last;i++)
   {
       cout<<*(arr+i);
       if(i<last -1)
       {
           cout<< " , ";
       }
   }
   cout<<"\n";
}
//function that sorts the array in ascending order
void bsort(int *arr,int last)
{
   int i,j,temp;
   //i -> 0 to last
   for(i = 0;i<last;i++)
   {
       //-> j = 0 to last - j - 1
       for(j = 0;j<last-i-1;j++)
       {
           //swap arr[j] with arr[j+1] if arr[j] is greater than arr[j+1]
           //below is the pointer notation for accessing array values at position j.
           if(*(arr + j) > *(arr+j+1))
           {
               temp = *(arr + j);
               *(arr+j) = *(arr+j+1);
               *(arr+j+1) = temp;
           }
       }
   }
}
int main()
{
   //intially set arr to null
   int *arr = NULL;
   //call readData() by passing arr address because we want to
   //assign memory and insert data.
   int len = readData(&arr);
   //if number of integers read are 0 then exit.
   if(len == 0)
   {
       cout<<"Due to error . No Integers are read in array. Qutting...";
       exit(1);
   }
   cout<<"\n------ Before Sort -----\n";
   //if not print the integers before sort
   writeToConsole(arr,len);
  
   //call bsort() to sort the array
   bsort(arr,len);
  
   cout<<"\n------ After Sort -----\n";
   //finally print the sorted arry to console.
   writeToConsole(arr,len);
   return 0;
}

/*
* ----- data.txt -------
10
9
23
2
24
12
10
5
7
6
7
*/
/*
* ----------- OUTPUT -----------
*
------ Before Sort -----

------- Array Elements --------

9 , 23 , 2 , 24 , 12 , 10 , 5 , 7 , 6 , 7

------ After Sort -----

------- Array Elements --------

2 , 5 , 6 , 7 , 7 , 9 , 10 , 12 , 23 , 24


------------------
(program exited with code: 0)

Press any key to continue . . .
*/

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
***C++ CODING*** Write a program for sorting a list of integers in ascending order using the...
***C++ CODING*** Write a program for sorting a list of integers in ascending order using the bubble sort algorithm. Requirements Implement the following functions: Implement a function called readData int *readData( )   The function returns a pointer that points to the locations with integers reading from the file data.txt. 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...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code int main(void) { int array[] = {10, 2, 7, 5, 15, 30, 8, 6}; // input array int arraySize = sizeof(array)/sizeof(array[0]); bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; //Note : "j" , "arraySize - j" are optimizations to the bubble sort algorithm j++; // j= sorted elements int i=0; /* "arraySize - j" is used...
Implement functions for insertion sort, quicksort, heapsort and merge sort that input an array of integers...
Implement functions for insertion sort, quicksort, heapsort and merge sort that input an array of integers and sort it in-place. Write a program that generates random integer arrays (hint: use seed appropriately to avoid generating same sequences) of lengths 10, 100, 1000, 10,000, 100,000, 1000,000, and then sorts each using each of the sorting functions from (a), and measures the time in nanoseconds. The program will repeat this process 30 times and will compute the average execution time for each...
Write a Java program that asks the user to enter an array of integers in the...
Write a Java program that asks the user to enter an array of integers in the main method. The program should prompt the user for the number of elements in the array and then the elements of the array. The program should then call a method named isSorted that accepts an array of and returns true if the list is in sorted (increasing) order and false otherwise. For example, if arrays named arr1 and arr2 store [10, 20, 30, 41,...
Please answer in C++ with the correct files (in bold). Thanks! Write a program that creates...
Please answer in C++ with the correct files (in bold). Thanks! Write a program that creates three identical arrays, list1, list2, and list3, of 5000 elements. The program then sorts list1 using bubble sort, list2 using selection sort, and list3 using insertion sort and outputs the number of comparisons and item assignments made by each sorting algorithm. Please use the file names listed below since your file will have the following components: Ch18_Ex15.cpp searchSortAlgorithms.h
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    //...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    // STEP 1 -- Make sorting methods generic    ///////////////////////////////////////////////       /**    * Re-orders the contents given array using the insertion sort algorithm.    *    * @param data The array to be sorted.    */    //TODO: Make me generic to work on any kind of Comparable data!    public static void insertionSort(int[] data)    {        int insert; // temporary...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF A RUNNING COMPILER QUESTION: 1) Fibonacci sequence is a sequence in which every number after the first two is the sum of the two preceding ones. Write a C++ program that takes a number n from user and populate an array with first n Fibonacci numbers. For example: For n=10 Fibonacci Numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 2): Write...
Finish the code wherever it says TODO /**    * Node type for this list. Each...
Finish the code wherever it says TODO /**    * Node type for this list. Each node holds a maximum of nodeSize elements in an    * array. Empty slots are null.    */    private class Node {        /**        * Array of actual data elements.        */        // Unchecked warning unavoidable.        public E[] data = (E[]) new Comparable[nodeSize];        /**        * Link to next node.       ...
This program is in C++, And please consider " sort pass #" for the output: Write...
This program is in C++, And please consider " sort pass #" for the output: Write a program that uses two identical arrays of eight integers. It should display the contents of the first array, then call a function to sort it using an ascending order bubble sort, modified to print out the array contents after each pass of the sort. Next the program should display the contents of the second array, then call a function to sort it using...
Write a code in c++ using linear insertion following the steps below. Comment your work. 1....
Write a code in c++ using linear insertion following the steps below. Comment your work. 1.    Ask the user for the name of a file containing data. If it does not exist, the program should display an error, then ask for a new file name. Entering an asterisk (*) as the first and only character on a line should terminate the program. 2.     You can use a statically-allocated one-dimensional array of doubles for this with length 100. You...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT