/* This program demonstrates * 1. Right Array Shift * 2. Bubble Sort */ /* Declare the functions here * when we pass an array into the function, we don't have to mention the size * the array. Mentioning it won't result in an error, but it is not necessary. * However, we have to specify it is an array, by using the [] * * Function names are self-descriptive here. They are described while being defined. */ void sort(double arr[], int size); void rightArrayShift(double arr[], int size); int main() { double arr[10]; // declare the array const int NUM = 10; //accept array values from the user cout<<"\nEnter values for the array: "; for(int i=0; i<10; i++) { cin>>arr[i]; } rightArrayShift(arr, NUM); cout<<"\nAfter right shift:\n"; for(int i=0; i< 10; i++) { cout<< arr[i]<<"\t"; } sort(arr, NUM); cout<<"\nAfter sorting:\n"; for(int i=0; i< 10; i++) { cout<< arr[i]<<"\t"; } return 0; } /* function rightShift * parameters - array, and its size * returns nothing * * Moves every element in the array one step to the right * N-1 moves * start at the end of the array * * 12 65 7 4 19 * 0 12 65 7 4 * * Elemnt in index 3 moves to index 4 * Element in index 2 moves to index 3 * element in index 1 moves to index 2 * * element in index i-1 moves to index i */ void rightArrayShift(double arr[], int size) { for(int i=size-1; i>0; i--) { arr[i] = arr[i-1]; } arr[0] = 0; } /* function sort * parameters - array and its size * returns nothing * * Sorts the array elements in ascending order * Naive Bubble Sort * * 10 98 27 -6 41 5 - size 6 * N-1 iterations * Iteration 0: elements 0 through 5 * Comparisons: 10 & 98, 98 & 27 swap, 98 & -6 swap, 98 & 41 swap, 98 & 5 swap (N-1 comparisons) * 10 27 -6 41 5 98 * 98 is in the right spot * * Iteration1: elements 0 through 4 * Comparisons: 10 & 27, 27 & -6 swap, 27 & 41, 41 & 5 swap ( N - 1 -1 comparisons) * 10 -6 27 5 41 | 98 * 41 and 98 are in the right spots * * Iteration 2: elements 0 through 3 * Comparisons: 10 & -6 swap, 10 & 27, 27 & 5 swap (N -1 -2 comparisons) * -6 10 5 27 | 41 98 * 27, 41 and 98 are in the right spots * * Iteration 3: elements 0 through 2 * Comparions: -6 & 10, 10 & 5 swap (N -1 - 3 comparisons) * -6 5 10 | 27 41 98 * 10, 27, 41 and 98 are in the right spots * * Iteration 4: elements 0 through 1 (N -1 - 4 comparisons) * Comparisons: -6 & 5 * -6 5 | 10 27 41 98 * * Array is sorted * * N-1 iterations * For each iteration, N-1 - iteration no. of comparisons * If numbers are out of order, swap them */ void sort(int arr[], int size) { for(int i=0; i< size-1; i++) { for(int j=0; j< size -1 - i; j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }