我使用以下方法实现Dobly链接列表:import java.util.LinkedList;带有气泡的对作业进行排序。在对排序和链接列表进行研究之后,我了解到我不应该使用索引对链表进行冒泡排序,因为链接列表中不存在indeces,或者成功实施太麻烦。使用Bubble实现双链表列表
所以,读过之后,我写了下面的代码,但是我仍然不确定自己是否在正确的道路上。
我需要一些帮助来理解气泡排序实现背后的逻辑,并使用一个链表。
另外,我需要确保我是否有效地走正确的路,或者如果我在这个编码练习中尝试完全错误。
//This for loop sorts the smaller part of the bubble sort.
for(int i = 0; i < cars.size() - 1; i++)
{ //This part creates the second "larger" part of the bubble sort.
for(int j = i + 1; j < cars.size(); j++)
{
//Did I do this part correctly? This is where the swap and sort of the bubble sort takes //place.
//Obviously, I am using the comparable interface, since I am using the compareTo method.
//
//with the bubblesort, all elements must be greater than zero because for the bubble //sort, 0 is the smallest element in a set of integers.
if(cars.get(i).getName().compareTo(cars.get(j).getName()) > 0)
{
CarName cari = cars.get(i);
CarName CarNamej = cars.get(j);
cars.remove(i);
cars.add(i, carj);
cars.remove(j);
cars.add(j, cari);
}
}
}
}
我使用它来输出这种方法的主要方法输出排序结果:
bubbleSort(cars);
我是正确的,还是我做一些完全错误的在我所有的代码?
我认为你应该先用一种方法完成问题,然后询问是否有问题 –
这就是问题所在,我用整数格式对一组数据进行排序,所以如果我用bubbleSort是我编码的方式吗? – edxyz