链接列表冒泡排序方法不排序元素

时间:2017-09-18 01:08:13

标签: java linked-list nodes bubble-sort

我正在尝试使用冒泡排序方法对链接列表进行排序,但是当我尝试对元素进行排序时,它们仍然未排序。当我调用我的链接方法时,它构建一个带有参数n和m的链表,它表示链表的长度,它表示一组随机整数m-1

节点类

public class iNode{
public int item;
public iNode next;

public iNode(int i, iNode n){ 
    item = i; 
    next = n; 
}
public iNode(int i){ 
    item = i; 
    next = null; 
}
// Node class
public int getItem() {
    return this.item;
}

节点列表类

public class iNode_List {

public  static iNode head;
public static int size;

public  iNode_List(){
    this.head = null;
    this.size = 0;
}


public static iNode linked(int n, int m){ // builds linked list 

    iNode previous;
    iNode current;

    int i = 0;
    previous = null;
    while (i < n) {
        current = new iNode(ThreadLocalRandom.current().nextInt(0, m-1), previous);
        previous = current;
        head = current;
        i++;
    }
    return previous;
}

public static void print() { // prints linked list
    iNode currentNode = head;
    while(currentNode != null) {
        int data = currentNode.getItem();
        System.out.println(data);
        currentNode = currentNode.next;
    }

}



public static void Bubble_Sort (){ // bubble sort method
    if (size > 1) {
        for (int i = 0; i < size; i++ ) {
            iNode currentNode = head;
            iNode next = head.next;
            for (int j = 0; j < size - 1; j++) {
                if (currentNode.item > next.item) {
                    int temp = currentNode.item;
                    currentNode.item = next.item;
                    next.item = temp;
                } 
                currentNode = next;
                next = next.next;                   
            } 
        }
    }

}

列出班级

public class list {

public static void main (String [] args) throws IOException{
    iNode_List x = new iNode_List();
    int choice;

    x.linked(10, 9);
    x.print();

    System.out.println();
    System.out.println("Which method would you like to implement? "); // method --------
    Scanner scan = new Scanner (System.in);
    choice = scan.nextInt();

    switch (choice) {
    case 1 : Compare_Loop(x) ; 
    break ;
    case 2 : Bubble_Sort( x) ;
    break ;
    case 3 :  Merge_Sort( x);
    break ;
    case 4 : Boolean( x);
    break ;
    }

}

public static void Compare_Loop (iNode_List x){
    System.out.println();
    x.Compare_Loop();
    x.print();
}

public static void Bubble_Sort(iNode_List x){
    System.out.println();
    x.Bubble_Sort();
    x.print();
}

public static void Merge_Sort(iNode_List x){
    System.out.println();
    x.Merge_Sort(null);
    x.print();
}

public static void Boolean (iNode_List x){
    System.out.println();
    //x.Boolean();
    x.print();
}

0 个答案:

没有答案