How to sort a linked list using bubble-sort?

后端 未结 5 644
夕颜
夕颜 2020-12-03 02:14

I am trying to use bubble-sort in order to sort a linked list. I use curr and trail in order to traverse thru the list. curr is supposed to be one step ahead of trail always

5条回答
  •  情歌与酒
    2020-12-03 02:50

    Bubble sort using array can be easily modified to bubble sort using linked list

    // Using array
        for(int i=0;iar[j+1]){
                    int temp = ar[j];
                    ar[j]=ar[j+1];
                    ar[j+1] = temp;
                }
            }
        }
    
    // Using linkedlist
        void bubblesortlinkedlist(Node head){
            Node i= head,j=head;
            while(i!=null){
                while(j.next!=null){
                    if(j.data>j.next.data){
                        int temp = j.data;
                        j.data = j.next.data;
                        j.next.data = temp;
                    }
                    j=j.next;
                }
                j=head;
                i=i.next;
            }
        }
    

提交回复
热议问题