我在C ++中为链接列表
执行了这种排序功能void sort()
{
node* ctr;
node* innerctr;
info temp;
node* max;
ctr = start;
while(ctr!=NULL)
{
innerctr=ctr->next;
max=ctr;
while(innerctr!=NULL)
{
if((innerctr->student.name) > (max->student.name))
{
max=innerctr;
}
innerctr=innerctr->next;
}
//swapping...
ctr=ctr->next;
}
}
我需要在Java中做类似的事情,我想使用LinkedList ready类,但我有点困惑,因为没有指针。
答案 0 :(得分:1)
检查java.util.Collections.sort。没有必要在Java中实现排序等,它都在JDK中。
答案 1 :(得分:0)
public static void selectionSort2(int[] x) {
for (int i=0; i<x.length-1; i++) {
int minIndex = i; // Index of smallest remaining value.
for (int j=i+1; j<x.length; j++) {
if (x[minIndex] > x[j]) {
minIndex = j; // Remember index of new minimum
}
}
if (minIndex != i) {
//... Exchange current element with smallest remaining.
int temp = x[i];
x[i] = x[minIndex];
x[minIndex] = temp;
}
}
}
答案 2 :(得分:0)
尽可能少的修改,几乎与Java相同:
class Student {String name = "Joe Doe";}
class Node {
Node next;
Student student;
}
class Info {}
public class NodeSorter {
Node start;
void sort()
{
Node ctr;
Node innerctr;
Info temp;
Node max;
ctr = start;
while (ctr != null)
{
innerctr = ctr.next;
max=ctr;
while (innerctr != null)
{
if ((innerctr.student.name).compareTo (max.student.name) > 0)
{
max = innerctr;
}
innerctr=innerctr.next;
}
//swapping...
ctr = ctr.next;
}
}
}
这是改进版本,类型为“Student”作为Node的参数:
class Student implements Comparable <Student> {
String name = "Joe Doe";
public int compareTo (Student other) {
if (other == null) return 1;
return name.compareTo (other.name);
}
}
class Node <T> {
Node <T> next;
T value;
}
class Info {}
public class NodeSorter {
Node <Comparable> start;
void sort ()
{
Node <Comparable> ctr;
Node <Comparable> innerctr;
Info temp;
Node <Comparable> max;
ctr = start;
while (ctr != null)
{
innerctr = ctr.next;
max=ctr;
while (innerctr != null)
{
if ((innerctr.value).compareTo (max.value) > 0)
{
max = innerctr;
}
innerctr=innerctr.next;
}
//swapping...
ctr = ctr.next;
}
}
}
未指定“开始”的问题是从您继承的。