Insertion sort program with counting number of swaps

I took this code somewhere off internet, i want the output to display the number of swaps and sorted data, can someone help me with modifying this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  //Variables:
//double arr[]: An array to store and sort  elements.
//int swaps: Integer variable to count the number of swaps performed.

#include<iostream>

int main()
{
    using namespace std;

    int arr[100]; //Declare our array and initialize to 0
    int n,swaps=0;    //Variable to count the number of swaps performed

    cout<<"Insertion sort Demonstration."<<endl<<endl;
cout<<"enter value of n: \n";
cin>>n;
    for (int i=0;i<n;i++)    //To traverse through the array 8 times and accept 8 numbers
    {
        cout<<"Enter element number "<<i+1<<": "; //We use i+1 just to start the display of numbers from 1 rather than 0
        cin>>arr[i];

        int j = i;
        while(j>0 && arr[j]<arr[j-1])    //Runs until the new number has been placed in its correct place
        {
            swap(arr[j],arr[j-1]);    //Swap if the elements are out of order.
            swaps++;    //Increase swap counter
            j--;    //decrease array index
        }
    }

    cout<<endl<<"Array After Sorting = ";
    for(int i=0;i<8;i++)    //Loop to print our sorted array.
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;

    cout<<"Total number of swaps performed: "<<swaps<<endl<<endl;

    cin.get();
    return 0;
}

line 32: replace 8 with n
Topic archived. No new replies allowed.