Answer to Question #59769 in C++ for PRIYA

Question #59769
Which of the following sorting algorithms in its typical implementation gives best
performance when applied on an array which is sorted or almost sorted (maximum 1 or two
elements are misplaced).
a.heap sort
b.quick sort
c.insertion sort
d.merge sort
NOTE: Write a program for the correct option and get the input from the user
1
Expert's answer
2016-05-11T08:55:03-0400
C. Insertion Sort

#include <iostream>
#include <vector>

using namespace std;

int main() {
unsigned size;
cout << "Input size of array (count of elements): ";
cin >> size;
vector<int> arr(size);
for (unsigned i = 0; i < arr.size(); i++) {
cout << "Input " << i << "th element of the array (" << i << "th number): ";
cin >> arr[i];
}
cout << endl;
// Start of insertion sort
for (unsigned i = 1; i < arr.size(); i++) {
int j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
// End of insertion sort
for (unsigned i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
cout << endl;
system("pause");
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS