开发者

Array swap an Array

Write a function called swap which has a prototype of void swap (int&, int&); to swap two neighbors that are not in increasing order.

here what i have so far

include <iostream>
using namespace std;
int main()
{
    int array[]={34, 21, 89,56,78,2,14,56,0,99};
    int countComparisons=0;

    cout<<"Original List: ";
    for (int i=0; i<=9; i++) cout<<a[i]<<" "; cout<<endl; //print array
    for (int start=0; start<=9;start++) //outer loop
    {
        for (int i=0; i<9; i++)  //inner loop
        {
            countComparisons++;
            if (array[i]>array[i+1])
            {

        }
    }
    cout<<"\nFinal List: ";
    for (int i=0; i<=9; i++) cout<<a[i]<<" "; cout<<endl; //print array
    cout <<"Number of com开发者_开发百科parions "<<countComparisons<<endl;
    return 0;
}

and the output is

Original List: 34 21 89 56 78 2 14 56 0 99
swapped 34 with 21
21 34 89 56 78 2 14 56 0 99
swapped 89 with 56
21 34 56 89 78 2 14 56 0 99
swapped 89 with 78
21 34 56 78 89 2 14 56 0 99
swapped 89 with 2
21 34 56 78 2 89 14 56 0 99
swapped 89 with 14
21 34 56 78 2 14 89 56 0 99
swapped 89 with 56
21 34 56 78 2 14 56 89 0 99
swapped 89 with 0
21 34 56 78 2 14 56 0 89 99
swapped 78 with 2
21 34 56 2 78 14 56 0 89 99
swapped 78 with 14
21 34 56 2 14 78 56 0 89 99
swapped 78 with 56
21 34 56 2 14 56 78 0 89 99
swapped 78 with 0
21 34 56 2 14 56 0 78 89 99
swapped 56 with 2
21 34 2 56 14 56 0 78 89 99
swapped 56 with 14
21 34 2 14 56 56 0 78 89 99
swapped 56 with 0
21 34 2 14 56 0 56 78 89 99
swapped 34 with 2
21 2 34 14 56 0 56 78 89 99
swapped 34 with 14
21 2 14 34 56 0 56 78 89 99
swapped 56 with 0
21 2 14 34 0 56 56 78 89 99
swapped 21 with 2
2 21 14 34 0 56 56 78 89 99
swapped 21 with 14
2 14 21 34 0 56 56 78 89 99
swapped 34 with 0
2 14 21 0 34 56 56 78 89 99
swapped 21 with 0
2 14 0 21 34 56 56 78 89 99
swapped 14 with 0
2 0 14 21 34 56 56 78 89 99
swapped 2 with 0
0 2 14 21 34 56 56 78 89 99

Final List: 0 2 14 21 34 56 56 78 89 99
Number of comparions 90

Process returned 0 (0x0)   execution time : 0.031 s
Press any key to continue.

any idea how to do this . i never learn how to swap the array

thank you


Write a function called swap which has a prototype of void swap (int&, int&); to swap two neighbors that are not in increasing order.

Pseudocode:

void swap(int& a, int& b)
{
    if b is smaller than a
    {
        store a in some new variable c
        store b in a
        store c in b
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜