如何在数组列表中使用此冒泡排序?

时间:2019-02-18 21:59:48

标签: java arraylist bubble-sort

我想为我的ArrayList使用bubble sort,但是遇到了一些问题。请帮助我。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package j1.s.p0001;

import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author Ak47pc
 */
public class J1SP0001 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        bubble();

    }

    public static void bubble() {
        int sum = 0;
        ArrayList<String> obj = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of Array: ");
        String ip = sc.next();
        try {
            for (int i = 0; i < Integer.parseInt(ip); i++) {
                obj.add(sc.next());
                sum += 1;
            }
        } catch (Exception e) {
            System.out.println("Please input a number!");
        }

        System.out.println(obj);


    }

}

1 个答案:

答案 0 :(得分:0)

我认为这可能对您有所帮助。 导入java.util.ArrayList;

public class Sort{
    private static ArrayList<String> list = new ArrayList<String>();

    public static ArrayList<String> sortByName(String [] input) {
        String temp;
        for (int i=0; i< input.length; i++){
            for(int j= i; j< input.length-1; j++){
                char first = input[i].charAt(0);
                char sec = input[j +1].charAt(0);
                 if (first < sec)  {
                     temp = input[j +1];
                     input[j +1] = input[i];        
                     input[i] = temp;
                 }
             }
            list.add(input[i]);
         }

        return list;
    }

    public static void main(String[] args) {
        String string[] =  {"XXX", "YYY" , "ZZZ", "QQQ", "AAA"};
        bubbleSortByName(string);
    }
}