编写一个程序,用 选择法 对数组 a[]={5,4,8,9,7,2,6,5}进行从大到小的排序,和从小到大的排序

public class SortTest {
    public static void main(String[] args) {
        int[] a= { 5, 4, 8, 9, 7, 2, 6, 5, 10 };
        int[] b = selectMaxToMinSort(a);
        for (int value : b) {
            System.out.print(value + " ");
        }
    }

    public static int[] selectMinToMaxSort(int[] input) {
        for (int i = 0; i < input.length; i++) {
            int temp = 9999;
            int index = 0;
            for (int j = i; j < input.length; j++) {
                if (temp > input[j]) {
                    temp = input[j];
                    index = j;
                }
            }
            if (index != 0) {
                int t = input[index];
                input[index] = input[i];
                input[i] = t;
            }
        }
        return input;
    }

    public static int[] selectMaxToMinSort(int[] input) {
        for (int i = 0; i < input.length; i++) {
            int temp = -9999;
            int index = 0;
            for (int j = i; j < input.length; j++) {
                if (temp < input[j]) {
                    temp = input[j];
                    index = j;
                }
            }
            if (index != 0) {
                int t = input[index];
                input[index] = input[i];
                input[i] = t;
            }
        }
        return input;
    }
}

用同一个函数名对n个数据进行从小到大排序 用函数模板

                        
                
#include <iostream>
using namespace std;
template <class T>
void sort(T* a, int n)
{
 int t;
 T temp; 
 for (int i=0; i<n-1; i++) 
 { 
  t=i;
  for (int j=i+1; j<n; j++) 
  { 
   if (*(a+t)>*(a+j))
    t=j; 
  } 
  temp=*(a+i);
  *(a+i)=*(a+t); 
  *(a+t)=temp; 
 }
}
static float arr0[6]={2.0,65.0,9.0,78.0,88.0,-2.0};
static double arr1[6]={558.0,999.0,123.0,222.0,55.0,456.0};
static int arr2[6]={123,456,789,654,321,5};
void main()
{
 cout<<"float exp."<<endl;
 for (int i=0; i<6; i++)
 {
  cout<<arr0[i]<<" ";
 }
 cout<<endl;
 sort(arr0, 6);
 for (i=0; i<6; i++)
 {
  cout<<arr0[i]<<" ";
 }
 cout<<endl;
 cout<<"double exp."<<endl;
 for (i=0; i<6; i++)
 {
  cout<<arr1[i]<<" ";
 }
 cout<<endl;
 sort(arr1, 6);
 for (i=0; i<6; i++)
 {
  cout<<arr1[i]<<" ";
 }
 cout<<endl;
 cout<<"int exp."<<endl;
 for (i=0; i<6; i++)
 {
  cout<<arr2[i]<<" ";
 }
 cout<<endl;
 sort(arr2, 6);
 for (i=0; i<6; i++)
 {
  cout<<arr2[i]<<" ";
 }
 cout<<endl;
}

原文:https://bbs.csdn.net/topics/200075670

猜你喜欢

转载自www.cnblogs.com/2549372994jing/p/10533433.html
今日推荐