Advertisement
Porr011

Lesson 11 activity 3

Apr 3rd, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. // function for displaying unsorted numbers
  6. // printing the numbers from the array from numbers,ARRAY_SIZE, and count
  7. void DisplayingUnsortedNumbers (int numbers[], int ARRAY_SIZE, int count)
  8. {
  9.     // Displaying the unsorted numbers
  10.     cout << " The numbers are: " ;
  11.     for (count = 0; count < ARRAY_SIZE; count ++)
  12.     cout << numbers [count] << " ";
  13.     cout << endl;
  14. }
  15.  
  16. // function for bubble sort
  17. // Sort numbers of the ARRAY_SIZE using Bubble Sort.
  18. void BubbleSort (int numbers[], int ARRAY_SIZE)
  19. {
  20.      bool swapped = true; // boolean function
  21.       int j = 0;
  22.       int tmp; // varible for temporary swap
  23.  
  24.     while (swapped) // while loop for the bubble sort
  25.     {
  26.     swapped = false;
  27.     j++;
  28.     for (int i = 0; i < ARRAY_SIZE - j; i++)
  29.     {
  30.     if (numbers[i] > numbers[i + 1])
  31.     {
  32.     tmp = numbers[i];
  33.     numbers[i] = numbers[i + 1];
  34.     numbers[i + 1] = tmp;
  35.     swapped = true;
  36.  
  37.     }
  38.  
  39.     }
  40.  
  41.     }
  42. } // bubble sort function ends here
  43.  
  44. //**************
  45. //* Main function
  46. //* opens our list and then stores this list into the array
  47. //* also has our functions for printing the array that is not sorted
  48. //* function for the bubble sort algorithm and prints the sorted numbers by returning
  49. //************
  50. int main ()
  51. {
  52.     int count = 0; // loop counter varible
  53.     string fileName="file.txt";
  54.     ifstream inputFile; // input file stream object
  55.    
  56.     //opening the file
  57.     inputFile.open(fileName); // Using ARRAY_SIZE and inputfile so that the text file works with any ammount of numbers
  58.      int ARRAY_SIZE;
  59.    inputFile >> ARRAY_SIZE;
  60.      int numbers[ARRAY_SIZE];
  61.    
  62.     //reading the numbers from the file then putting it into the array
  63.     while (count < ARRAY_SIZE && inputFile >> numbers [count])
  64.     count ++;
  65.    
  66.     // closing file
  67.     inputFile.close();
  68.    
  69.     //function for displaying unsorted numbers
  70.     DisplayingUnsortedNumbers(numbers, ARRAY_SIZE, count);
  71.    
  72.     // function for sorted numbers
  73.     BubbleSort(numbers, ARRAY_SIZE);
  74.    
  75.     cout << " The sorted numbers are: " ;
  76.      for (auto num: numbers)
  77.     {
  78.     cout << num << ' ' ;
  79.     }
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement