Java : Sort integer array without using Arrays.sort()

后端 未结 12 2605
滥情空心
滥情空心 2021-02-14 00:59

This is the instruction in one of the exercises in our Java class. Before anything else, I would like to say that I \'do my homework\' and I\'m not just being lazy asking someon

12条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-14 01:51

    Here is one simple solution

    public static void main(String[] args) {        
            //Without using Arrays.sort function
            int i;
            int nos[] = {12,9,-4,-1,3,10,34,12,11};
            System.out.print("Values before sorting: \n");
            for(i = 0; i < nos.length; i++)
                System.out.println( nos[i]+"  ");               
            sort(nos, nos.length);
            System.out.print("Values after sorting: \n");       
            for(i = 0; i  0) && (nos[j-1] > B)){
                nos[j] = nos[j-1];
                j--;
              }
              nos[j] = B;
            }
        }
    

    And the output is:

    Values before sorting:

    12
    9
    -4
    -1
    3
    10
    34
    12
    11

    Values after sorting:

    -4
    -1
    3
    9
    10
    11
    12
    12
    34

提交回复
热议问题