C++ Pointers, Sorting, Functions Objectives: use pointer notation instead of sta
ID: 3777481 • Letter: C
Question
C++ Pointers, Sorting, Functions
Objectives: use pointer notation instead of standard array notation, create function prototypes, create and use functions, implement pseudocode algorithms in C++, pass arrays to functions.
Overview: Implementing a pseudocode sorting algorithm in C++ and several functions that use pointers. You are given the main function, which will create the array, call one of your functions to do the sort, and then display the results.
Requirement:You must use prototypes for all of the functions other than main.You may not have any global variables.You must use pointers for all of the code that you write. You are not allowed to use [] to access elements of the array.
Pseudocode:The following is your pseudocode for the three functions you must implement.
Starting code:
Sample Run:
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::boolalpha;
using std::endl;
bool isSorted(int series[], int len);
void swap(int* ar, int pos1, int pos2);
void sort(int* series, int SIZE);
void sort2(int* nums, int left, int right);
int partition(int* nums, int left, int right);
int main(int argc, char* argv[]) {
const int SIZE = 100;
srand(time(NULL));
int* series = new int[SIZE];
for (int i=0; i<SIZE; i++) {
*(series+i) = rand() % (SIZE * 10);
}
cout << "The array is sorted: " << boolalpha << isSorted(series, SIZE) << endl;
cout << "Sorting...";
sort(series, SIZE);
cout << " The array is sorted: " << boolalpha << isSorted(series, SIZE) << endl;
if (series != NULL) delete[] series;
return 0;
}
bool isSorted(int* series, int len) {
bool sorted = true;
for (int i=1; i<len; i++) {
if (*(series+i-1) > *(series+i)) {
sorted = false;
break;
}
}
return sorted;
}
void sort(int* series, int SIZE){
sort2(series, 0, SIZE-1);
}
void sort2(int* nums, int left, int right){
if (left<right){
int p = partition(nums, left, right);
sort2(nums, left, p-1);
sort2(nums, p+1, right);
}
return;
}
int partition(int* nums, int left, int right){
int pivot = nums[right];
int i = left;
for(int j=left; j<right; j++){
if (nums[j]<=pivot){
int a = nums[i];
nums[i] = nums[j];
nums[j] = a;
i++;
}
}
int a = nums[i];
nums[i] = nums[right];
nums[right] = a;
return i;
}
void swap(int* ar, int pos1, int pos2) {
int temp = *(ar+pos1);
*(ar+pos1) = *(ar+pos2);
*(ar+pos2) = temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.