java代码选择排序 java选择排序函数

直接选择排序Java实现 About this application:
This application implements Straight Selection Sort algorithm which is described like this:
If there are N numbers find the minimum and exchange it with the first number then N numbers remained Continue to find the minimum number in the remained N numbers and exchange it with the second number Repeat this until all the numbers are in order
Note: This is SWT application so you need eclipse swt win win x _ v b jar eclipse jface_ I jar mands_ I jar This is for Eclipse
Source Code:
package selection sort;
import java util ArrayList;
import eclipse swt SWT;
import eclipse swt events KeyAdapter;
import eclipse swt events KeyEvent;
import eclipse swt events ModifyEvent;
import eclipse swt events ModifyListener;
import eclipse swt events SelectionAdapter;
import eclipse swt events SelectionEvent;
import eclipse swt layout FormAttachment;
import eclipse swt layout FormData;
import eclipse swt layout FormLayout;
import eclipse swt widgets Button;
import eclipse swt widgets Display;
import eclipse swt widgets Group;
import eclipse swt widgets Label;
import eclipse swt widgets Shell;
import eclipse swt widgets Text;
/**
* This application implements Straight Selection Sort algorithm which means
* get the minimum number from the numbers and exchange it with the first
* number then doing this for other numbers except the first number Repeat
* this until all numbers are in order If you have any suggestion or problem
* please e mail to
*
* @author vivien Data:
*/
public class StraightSelectionSort {
/** The string containing the number wait for sorted */
public String numString = new String();
public Text numText;
public Text resText;
public Button btSort;
public Label errorLabel;
/** The flag to indicate if there is any error for inputed numbers */
public boolean hasError = false;
/** The arrayList containing the double numbers wait for sorted */
public ArrayListDouble numList = new ArrayListDouble();
public static void main(String[] args) {
StraightSelectionSort selectionSort = new StraightSelectionSort();
selectionSort createControl();
}
/**
* Create the control for the interface
*/
public void createControl() {
Display display = new Display();
Shell shell = new Shell(display);
shell setBounds( );
// Set Title
shell setText( Straight selection sort );
FormLayout layout = new FormLayout();
shell setLayout(layout);
FormData fd = new FormData();
// The Start Sort button
btSort = new Button(shell SWT NONE | SWT CENTER);
btSort setText( Start Sort );
fd = new FormData();
fd height = ;
fd top = new FormAttachment( );
fd left = new FormAttachment( );
btSort setLayoutData(fd);
// The Input numbers group
Group numGroup = new Group(shell SWT NONE);
numGroup setText( Input numbers: );
numGroup setLayout(layout);
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment(btSort );
numGroup setLayoutData(fd);
// Label for input numbers
Label numLabel = new Label(numGroup SWT WRAP);
numLabel
setText( Please input the numbers you want to sort: (Note: Numbers need to be seperated by space) );
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
numLabel setLayoutData(fd);
// Text for input numbers
numText = new Text(numGroup SWT BORDER | SWT MULTI | SWT V_SCROLL
| SWT WRAP);
numText setToolTipText( Numbers need to be seperated by space );
fd = new FormData();
fd top = new FormAttachment(numLabel );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
numText setLayoutData(fd);
// The results group
Group resGroup = new Group(shell SWT NONE);
resGroup setText( The results: );
resGroup setLayout(layout);
fd = new FormData();
fd top = new FormAttachment(btSort );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
resGroup setLayoutData(fd);
// Label for results
Label resLabel = new Label(resGroup SWT WRAP);
resLabel
setText( The results after sorted are: (Note: Results are seperated by space) );
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
resLabel setLayoutData(fd);
// Text for results
resText = new Text(resGroup SWT BORDER | SWT MULTI | SWT V_SCROLL
| SWT WRAP);
resText setToolTipText( Results are seperated by space );
resText setEditable(false);
fd = new FormData();
fd top = new FormAttachment(resLabel );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
resText setLayoutData(fd);
// Label for showing error message
errorLabel = new Label(shell SWT NONE);
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
errorLabel setLayoutData(fd);
errorLabel setForeground(display getSystemColor(SWT COLOR_RED));
// Listen to the numText change
numText addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
numString = numText getText() trim();
hasError = false;
}
});
// If press Return focus go to Start Sort button and start sort
numText addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e keyCode == \r ) {
e doit = false;
btSort setFocus();
startSort();
}
}
});
// Listen to the button selection
btSort addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
startSort();
}
});
shell open();
while (!shell isDisposed()) {
if (!display readAndDispatch())
display sleep();
}
display dispose();
}
/**
* Get double values from string
*/
public void getDoubleFromString() {
int index = ;
// Split string using space
String[] splitedNumbers = numString split( );
if (numList size() != )
// Clear the arrayList for last used
numList clear();
for (int i = ; isplitedNumbers length; i) {
if (splitedNumbers[i] trim() length() != ) {
try {
numList add(indexDouble valueOf(splitedNumbers[i]));
} catch (NumberFormatException e) {
setErrorMessage( Please input the correct numbers );
hasError = true;
break;
}
}
}
}
/**
* Start sort the string containing numbers waited for sort
*/
public void startSort() {
if (numString != null)
if (numString trim() length() != ) {
getDoubleFromString();
startStraightSelectionSort();
setResults();
} else {
setErrorMessage( Please input numbers );
hasError = true;
}
}
/**
* Set the results to the results group
*/
public void setResults() {
if (!hasError) {
String resString = new String();
for (int i = ; inumList size(); i)
if (i != numList size() )
resString = resStringnumList get(i);
else
// If be the last string
resString = resStringnumList get(i);
resText setText(resString);
// Clear errorLabel
errorLabel setText( );
}
}
/**
* Sort the numbers using Straight selection Sort algorithm
*/
public void startStraightSelectionSort() {
int minPosition = ;
for (int j = ; jnumList size() ; j) {
minPosition = j;
for (int i = j; inumList size(); i) {
if (numList get(i)numList get(minPosition)) {
minPosition = i;
}
}
if (minPosition != j) {
// Exchange the minimum with the first number of the numbers
// waited for sort
double temp = numList get(j);
numList set(j numList get(minPosition));
numList set(minPosition temp);
}
}
}
/**
* Set the error message on the error Label
*
* @param errorString
*The string used for set on the errorLabel
*/
public void setErrorMessage(String errorString) {
errorLabel setText(errorString);
// Clear the text of results
resText setText( );
hasError = true;
}
}
Black box Test Case:
)All numbers are zero:
Java几种简单的排序源代码给你介绍4种排序方法及源码,供参考
1.冒泡排序
主要思路: 从前往后依次交换两个相邻的元素,大的交换到后面,这样每次大的数据就到后面,每一次遍历,最大的数据到达最后面 , 时间复杂度是O(n^2) 。
public static void bubbleSort(int[] arr){
for(int i =0; iarr.length - 1; i){
for(int j=0; jarr.length-1; j){
if(arr[j]arr[j 1]){
arr[j] = arr[j]^arr[j 1];
arr[j 1] = arr[j]^arr[j 1];
arr[j] = arr[j]^arr[j 1];
}
}
}
}
2.选择排序
主要思路:每次遍历序列,从中选取最小的元素放到最前面,n次选择后,前面就都是最小元素的排列了,时间复杂度是O(n^2) 。
public static void selectSort(int[] arr){
for(int i = 0; i arr.length -1; i){
for(int j = i 1; jarr.length; j){
if(arr[j]arr[i]){
arr[j] = arr[j]^arr[i];
arr[i] = arr[j]^arr[i];
arr[j] = arr[j]^arr[i];
}
}
}
}
3.插入排序
主要思路:使用了两层嵌套循环,逐个处理待排序的记录 。每个记录与前面已经排好序的记录序列进行比较,并将其插入到合适的位置 , 时间复杂度是O(n^2) 。
public static void insertionSort(int[] arr){
int j;
for(int p = 1; parr.length; p){
int temp = arr[p];//保存要插入的数据
//将无序中的数和前面有序的数据相比,将比它大的数,向后移动
for(j=p; j0temp arr[j-1]; j--){
arr[j] = arr[j-1];
}
//正确的位置设置成保存的数据
arr[j] = temp;
}
}
4.希尔排序
主要思路:用步长分组,每个分组进行插入排序,再慢慢减小步长,当步长为1的时候完成一次插入排序 , 希尔排序的时间复杂度是:O(nlogn)~O(n2),平均时间复杂度大致是O(n^1.5)
public static void shellSort(int[] arr){
int j ;
for(int gap = arr.length/2; gap0 ; gap/=2){
for(int i = gap; iarr.length; i){
int temp = arr[i];
for(j = i; j=gaptemparr[j-gap]; j-=gap){
arr[j] = arr[j-gap];
}
arr[j] = temp;
}
}
}
请给出java几种排序方法java常见的排序分为:
1 插入类排序
主要就是对于一个已经有序的序列中,插入一个新的记录 。它包括:直接插入排序 , 折半插入排序和希尔排序
2 交换类排序
这类排序的核心就是每次比较都要“交换”,在每一趟排序都会两两发生一系列的“交换”排序,但是每一趟排序都会让一个记录排序到它的最终位置上 。它包括:起泡排序,快速排序
3 选择类排序
每一趟排序都从一系列数据中选择一个最大或最小的记录,将它放置到第一个或最后一个为位置交换,只有在选择后才交换,比起交换类排序,减少了交换记录的时间 。属于它的排序:简单选择排序,堆排序
4 归并类排序
将两个或两个以上的有序序列合并成一个新的序列
5 基数排序
主要基于多个关键字排序的 。
下面针对上面所述的算法,讲解一些常用的java代码写的算法
二 插入类排序之直接插入排序
直接插入排序,一般对于已经有序的队列排序效果好 。
基本思想:每趟将一个待排序的关键字按照大小插入到已经排序好的位置上 。
算法思路,从后往前先找到要插入的位置,如果小于则就交换,将元素向后移动 , 将要插入数据插入该位置即可 。时间复杂度为O(n2),空间复杂度为O(1)
package sort.algorithm;
public class DirectInsertSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int data[] = { 2, 6, 10, 3, 9, 80, 1, 16, 27, 20 };
int temp, j;
for (int i = 1; idata.length; i) {
temp = data[i];
j = i - 1;
// 每次比较都是对于已经有序的
while (j = 0data[j]temp) {
data[j1] = data[j];
j--;
}
data[j1] = temp;
}
// 输出排序好的数据
for (int k = 0; kdata.length; k) {
System.out.print(data[k]"");
}
}
}
三 插入类排序之折半插入排序(二分法排序)
条件:在一个已经有序的队列中,插入一个新的元素
折半插入排序记录的比较次数与初始序列无关
思想:折半插入就是首先将队列中取最小位置low和最大位置high , 然后算出中间位置mid
将中间位置mid与待插入的数据data进行比较,
如果mid大于data,则就表示插入的数据在mid的左边,high=mid-1;
如果mid小于data,则就表示插入的数据在mid的右边,low=mid 1
最后整体进行右移操作 。
时间复杂度O(n2),空间复杂度O(1)
package sort.algorithm;
//折半插入排序
public class HalfInsertSort {
public static void main(String[] args) {
int data[] = { 2, 6, 10, 3, 9, 80, 1, 16, 27, 20 };
// 存放临时要插入的元素数据
int temp;
int low, mid, high;
for (int i = 1; idata.length; i) {
temp = data[i];
// 在待插入排序的序号之前进行折半插入
low = 0;
high = i - 1;
while (low = high) {
mid = (lowhigh) / 2;
if (tempdata[mid])
high = mid - 1;
else
// low=high的时候也就是找到了要插入的位置,
// 此时进入循环中,将low加1,则就是要插入的位置了
low = mid1;
}
// 找到了要插入的位置,从该位置一直到插入数据的位置之间数据向后移动
for (int j = i; j = low1; j--)
data[j] = data[j - 1];
// low已经代表了要插入的位置了
data[low] = temp;
}
for (int k = 0; kdata.length; k) {
System.out.print(data[k]"");
}
}
}
四 插入类排序之希尔排序
希尔排序,也叫缩小增量排序,目的就是尽可能的减少交换次数,每一个组内最后都是有序的 。
将待续按照某一种规则分为几个子序列,不断缩小规则,最后用一个直接插入排序合成
空间复杂度为O(1),时间复杂度为O(nlog2n)
算法先将要排序的一组数按某个增量d(n/2,n为要排序数的个数)分成若干组 , 每组中记录的下标相差d.对每组中全部元素进行直接插入排序,然后再用一个较小的增量(d/2)对它进行分组,在每组中再进行直接插入排序 。当增量减到1时,进行直接插入排序后,排序完成 。
package sort.algorithm;
public class ShellSort {
public static void main(String[] args) {
int a[] = { 1, 54, 6, 3, 78, 34, 12, 45, 56, 100 };
double d1 = a.length;
int temp = 0;
while (true)
{
//利用这个在将组内倍数减小
//这里依次为5,3,2,1
d1 = Math.ceil(d1 / 2);
//d为增量每个分组之间索引的增量
int d = (int) d1;
//每个分组内部排序
for (int x = 0; xd; x)
{
//组内利用直接插入排序
for (int i = xd; ia.length; i= d) {
int j = i - d;
temp = a[i];
for (; j = 0tempa[j]; j -= d) {
a[jd] = a[j];
}
a[jd] = temp;
}
}
if (d == 1)
break;
}
for (int i = 0; ia.length; i)
System.out.print(a[i] "");
}
}
五 交换类排序之冒泡排序
交换类排序核心就是每次比较都要进行交换
冒泡排序:是一种交换排序
每一趟比较相邻的元素 , 较若大小不同则就会发生交换 , 每一趟排序都能将一个元素放到它最终的位置!每一趟就进行比较 。
时间复杂度O(n2) , 空间复杂度O(1)
package sort.algorithm;
//冒泡排序:是一种交换排序
public class BubbleSort {
// 按照递增顺序排序
public static void main(String[] args) {
// TODO Auto-generated method stub
int data[] = { 2, 6, 10, 3, 9, 80, 1, 16, 27, 20, 13, 100, 37, 16 };
int temp = 0;
// 排序的比较趟数,每一趟都会将剩余最大数放在最后面
for (int i = 0; idata.length - 1; i) {
// 每一趟从开始进行比较,将该元素与其余的元素进行比较
for (int j = 0; jdata.length - 1; j) {
if (data[j]data[j1]) {
temp = data[j];
data[j] = data[j1];
data[j1] = temp;
}
}
}
for (int i = 0; idata.length; i)
System.out.print(data[i]" ");
}
}
求java选择排序代码及注释//简单选择排序,按自然顺序
public static void selectsort(int[] array){
int min, index, temp;
for(int i = 0; iarray.length - 1; i){// N - 1 趟
min = i;
//查找选择最小元素值的下标索引值
for(index = i1; indexarray.length; index){
if(array[min]array[index])
min = index;
}
//交换
if(min != i){
temp = array[min];
array[min] = array[i];
array[i] = temp;
}
}
}
java快速排序简单代码.example-btn{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.example-btn:hover{color:#fff;background-color:#47a447;border-color:#398439}.example-btn:active{background-image:none}div.example{width:98%;color:#000;background-color:#f6f4f0;background-color:#d0e69c;background-color:#dcecb5;background-color:#e5eecc;margin:0 0 5px 0;padding:5px;border:1px solid #d4d4d4;background-image:-webkit-linear-gradient(#fff,#e5eecc 100px);background-image:linear-gradient(#fff,#e5eecc 100px)}div.example_code{line-height:1.4em;width:98%;background-color:#fff;padding:5px;border:1px solid #d4d4d4;font-size:110%;font-family:Menlo,Monaco,Consolas,"Andale Mono","lucida console","Courier New",monospace;word-break:break-all;word-wrap:break-word}div.example_result{background-color:#fff;padding:4px;border:1px solid #d4d4d4;width:98%}div.code{width:98%;border:1px solid #d4d4d4;background-color:#f6f4f0;color:#444;padding:5px;margin:0}div.code div{font-size:110%}div.code div,div.code p,div.example_code p{font-family:"courier new"}pre{margin:15px auto;font:12px/20px Menlo,Monaco,Consolas,"Andale Mono","lucida console","Courier New",monospace;white-space:pre-wrap;word-break:break-all;word-wrap:break-word;border:1px solid #ddd;border-left-width:4px;padding:10px 15px}排序算法是《数据结构与算法》中最基本的算法之一 。排序算法可以分为内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大 , 一次不能容纳全部的排序记录,在排序过程中需要访问外存 。常见的内部排序算法有:插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序等 。以下是快速排序算法:
快速排序是由东尼·霍尔所发展的一种排序算法 。在平均状况下 , 排序 n 个项目要 Ο(nlogn) 次比较 。在最坏状况下则需要 Ο(n2) 次比较,但这种状况并不常见 。事实上,快速排序通常明显比其他 Ο(nlogn) 算法更快,因为它的内部循环(inner loop)可以在大部分的架构上很有效率地被实现出来 。
快速排序使用分治法(Divide and conquer)策略来把一个串行(list)分为两个子串行(sub-lists) 。
快速排序又是一种分而治之思想在排序算法上的典型应用 。本质上来看 , 快速排序应该算是在冒泡排序基础上的递归分治法 。
快速排序的名字起的是简单粗暴,因为一听到这个名字你就知道它存在的意义 , 就是快,而且效率高!它是处理大数据最快的排序算法之一了 。虽然 Worst Case 的时间复杂度达到了 O(n?),但是人家就是优秀,在大多数情况下都比平均时间复杂度为 O(n logn) 的排序算法表现要更好,可是这是为什么呢,我也不知道 。好在我的强迫症又犯了,查了 N 多资料终于在《算法艺术与信息学竞赛》上找到了满意的答案:
快速排序的最坏运行情况是 O(n?),比如说顺序数列的快排 。但它的平摊期望时间是 O(nlogn) , 且 O(nlogn) 记号中隐含的常数因子很小,比复杂度稳定等于 O(nlogn) 的归并排序要小很多 。所以,对绝大多数顺序性较弱的随机数列而言 , 快速排序总是优于归并排序 。
1. 算法步骤
从数列中挑出一个元素,称为 "基准"(pivot);
重新排序数列 , 所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边) 。在这个分区退出之后,该基准就处于数列的中间位置 。这个称为分区(partition)操作;
递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序;
2. 动图演示
代码实现JavaScript实例functionquickSort ( arr ,left ,right ){
varlen=arr. length,
partitionIndex ,
left=typeofleft!='number'?0:left ,
right=typeofright!='number'?len-1:right ;
if( left
java 编写一个程序,输入3个整数,然后程序将对这三个整数按照从大到小进行排列可以实现比较器Comparator来定制排序方案,同时使用Colletions.sort的方式进行排序 , 代码如下:
public void sortDesc(ListLong s){
Collections.sort(s, new ComparatorLong() {
public int compare(Long o1, Long o2) {
Long result = o2 - o1;
return result.intValue();
}
});
s.forEach(item-{
System.out.print(item" ");
});
}
同时常用的比较排序算法主要有:冒泡排序,选择排序,插入排序,归并排序 , 堆排序 , 快速排序等 。
java的冒泡排序实现如下:
public static void bubbleSort(int []arr) {for(int i =0;iarr.length-1;i) {for(int j=0;jarr.length-i-1;j) {//-1为了防止溢出if(arr[j]arr[j 1]) {int temp = arr[j];arr[j]=arr[j 1];arr[j 1]=temp;}}}}
还有非比较排序,时间复杂度可以达到O(n),主要有:计数排序,基数排序,桶排序等 。
【java代码选择排序 java选择排序函数】关于java代码选择排序和java选择排序函数的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读