JAVA怎样用链表来实现冒泡排序,我需要整个编程过程,谢谢

2024-11-26 18:26:53
推荐回答(2个)
回答1:

Java程序:

import java.util.Scanner;

public class TesLinkList {
public static void main(String[] args) {
LinkList list = new LinkList();
Scanner scan = new Scanner(System.in);
int i, size;

System.out.print("请输入链表的大小:");
size = scan.nextInt();
for(i=0; i list.addAt(i, scan.nextInt());
}

System.out.println("链表结点一览:");
list.listAll();

list.bubbleSort();

System.out.println("排序后的链表结点一览:");
list.listAll();
}
}

/**
* 链表结点类
*/
class Node{
private int data;
private Node next; //链表结点的指针域,指向直接后继结点

public Node(){
next = null;
}

public Node(int data, Node next){
this.data = data;
this.next = next;
}

public int getData(){
return this.data;
}

public void setData(int data){
this.data = data;
}

public Node getNext(){
return this.next;
}

public void setNext(Node next){
this.next = next;
}
}

/**
* 链表类
*/
class LinkList{
private Node head = null; //头结点指针
private int size = 0;

public LinkList(){
head = new Node();
size = 0;
}

//在i位置插入元素elem
public boolean addAt(int i, int elem) {
if(i < 0 || i > size){
return false;
}

Node pre,curr;
int pos;
for(pre=head; i>0 && pre.getNext()!=null; i--,pre=pre.getNext());
curr = new Node(elem, pre.getNext());
pre.setNext(curr);
size++;
return true;
}

public Node getHead(){
return this.head;
}

public void setHead(Node head){
this.head = head;
}

public int getSize(){
return this.size;
}

public boolean isEmpty(){
return (size==0);
}

public void listAll(){
for(Node curr=head.getNext(); curr!=null; curr=curr.getNext()){
System.out.print(curr.getData() + "\t");
}
System.out.println();
}

public void bubbleSort(){
Node p, q;
int temp;
for(p=head.getNext(); p.getNext()!=null; p=p.getNext()){
for(q=head.getNext(); q.getNext()!=null; q=q.getNext()){
if(q.getData() > q.getNext().getData()){
temp = q.getData();
q.setData(q.getNext().getData());
q.getNext().setData(temp);
}
}
}
}
}

运行测试:
请输入链表的大小:4
1
2
4
3
链表结点一览:
1 2 4 3
排序后的链表结点一览:
1 2 3 4

回答2:

public static void main(String[] args) {
int[] array = {3,2,4,1};
System.out.println(Arrays.toString(array));
int x = array.length;
for (int i = 0; i < x; i++) {
for (int j = 0; j < array.length; j++) {
if(j+1 if(array[j]>array[j+1]){
int temp = array[j+1];
array[j+1]=array[j];
array[j]=temp;
}
}

}
System.out.println(Arrays.toString(array));
x = array.length-1;
}

}