I have an exercise for sort an array in c++. I'm coding with command line programming from turbo c++.

有帮助吗?

解决方案 2

Here is how i did it. Hope this is what you mean.

  • Read the command line arguments
  • Convert the string to integer using atoi function
  • Sort using any sorting algorithm (bubble sort used here)
  • Print the result

To see how bubble sort works check out this.

    #include<iostream.h>
    #include<stdlib.h>

    int main(int argc, char *argv[])
    {
     int i,j,temp, arr[10];

     for(i=1; i<argc; ++i)
     {
      arr[i-1] = atoi(argv[i]);
     }

     /* Sort the array using bubble sort alogrithm */
     for(i=0; i<argc-2; ++i)
     {
      for(j=0; j<argc-2; ++j)
      {
       if(arr[j] > arr[j+1])
       {
        temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
       }
      }
     }

     /* Print the result */
     cout<<"Sorted array : ";
     for(i=0; i<argc-1; ++i)
     {
      cout<<" "<<arr[i];
     }
     return 0;
    }

其他提示

You can use this code, it uses bubble sort algorithm.

#include <stdio.h>
#include <iostream>

using namespace std;

void sort(int *,int);

int main()
{
    int arr[10] = {2,3,4,12,5,0,2,5,1,20};
    sort(arr,10);
for(int i = 0;i<10;i++)
    cout << arr[i] << " ";
    return 0;
}

void sort(int * ar,int length)
{
    for(int i = 0;i<length;i++)
    {
        for(int j = i;j<length;j++)
        {
            if(ar[j] < ar[i])
            {
                int swap = ar[i];
                ar[i] = ar[j];
                ar[j] = swap;
            }
        }
    }
}

EDIT:

As I said it's based on the bubble algorithm. It sequentially checks the indexes from first one to last one and automatically puts the smallest number in first place, second smallest in second place and so on. You can see here or here for more information.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top