梦想飞翔

自强不息
posts - 111, comments - 30, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

三种常见java算法

Posted on 2007-02-04 23:07 love1563 阅读(342) 评论(0)  编辑  收藏

public class BubbleSort
{

public BubbleSort()
{

}

public static void main ( String args[] )
{

int data[] = { 63, 56, 98, 12, 24 };

int n = data.length;

// bubblesort(data, n);//冒泡排序
//selectionSort(data, n);//选择排序
insertionSort(data,n);//插入排序
for (int i = 0; i < n; i++)
{

System.out.println(data[i]);

}

}

public static void swap ( int data[] , int i , int j )
{

int temp;
temp = data[i];
data[i] = data[j];
data[j] = temp;
}

/*

  • 冒泡排序

*/
public static void bubblesort ( int data[] , int n )
{

int numsorted = 0;
int index;
while (numsorted < n)
{

for (index = 1; index < n – numsorted; index++)
{

if (data[index – 1] > data[index])
swap(data, index – 1, index);

}
numsorted++;

}

}

/*

  • 选择排序

*/
public static void selectionSort ( int data[] , int n )
{

int numUnsorted = n;
int index;
int max;
while (numUnsorted > 0)
{

max = 0;
for (index = 1; index < numUnsorted; index++)
{

if (data[max] < data[index])
max = index;

}
swap(data, max, numUnsorted – 1);
numUnsorted — ;

}
}

/*

  • 插入排序

*/
public static void insertionSort ( int data[] , int n )
{

int numSorted = 1;
int index;
while (numSorted < n)
{

int temp = data[numSorted];
for (index = numSorted; index > 0; index — )
{

if (temp < data[index – 1])
{

data[index] = data[index – 1];
} else
{

break;
}

}
data[index] = temp;
numSorted++;
}

}

}


只有注册用户登录后才能发表评论。


网站导航: