Write a C++ program that allows the user to enter the values for an array of int
ID: 3635055 • Letter: W
Question
Write a C++ program that allows the user to enter the values for an array of integers, and select between sorting them in ascending or descending order. Print the unsorted and sorted array and the array after each pass. Use a function for the selection sort.The program should look like this when complied correctly.(see below)
Enter the number of values in the array [integer]: 6
Enter element value #1: 11
Enter element value #2: 7
Enter element value #3: 23
Enter element value #4: 1
Enter element value #5: 16
Enter element value #6: 15
Enter sorting order [A for ascending, D for descending]: A
Unsorted array: 11 7 23 1 16 15
Pass 1: 1 7 23 11 16 15
Pass 2: 1 7 23 11 16 15
Pass 3: 1 7 11 23 16 15
Pass 4: 1 7 11 15 16 23
Pass 5: 1 7 11 15 16 23
Array sorted in ascending order: 1 7 11 15 16 23
Explanation / Answer
please rate - thanks
#include <iostream>
using namespace std;
void print(int[],int);
void ascending(int[],int);
void decending(int[],int);
void swap(int&,int&);
int main()
{int a[100],n,i;
char choice;
cout<<"Enter the number of values in the array [integer]: ";
cin>>n;
for(i=0;i<n;i++)
{cout<<"Enter element value #"<<i+1<<": ";
cin>>a[i];
}
cout<<" Enter sorting order [A for ascending, D for descending]: ";
cin>>choice;
cout<<"Unsorted array: ";
print(a,n);
cout<<endl;
if(choice=='A')
{ascending(a,n);
cout<<" array sorted in ascending order: ";
print(a,n);
}
else
{decending(a,n);
cout<<" array sorted in decending order: ";
print(a,n);
}
return 0;
}
void swap(int& a,int& b)
{int t;
t=a;
a=b;
b=t;
}
void print(int a[],int n)
{int i;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
void ascending(int a[],int n)
{int i,j,min,index,;
for(i=0;i<n-1; i++)
{index=i;
min=a[i];
for(j=i+1;j<n;j++)
{if(min>a[j])
{index=j;
min=a[j];
}
}
swap(a[i],a[index]);
cout<<"pass "<<i+1<<":";
print(a,n);
}
}
void decending(int a[],int n)
{int i,j,min,index,;
for(i=0;i<n-1; i++)
{index=i;
min=a[i];
for(j=i+1;j<n;j++)
{if(min<a[j])
{index=j;
min=a[j];
}
}
swap(a[i],a[index]);
cout<<"pass "<<i+1<<":";
print(a,n);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.