「java直接选择排序」java中选择排序

博主:adminadmin 2022-12-31 09:00:11 646

今天给各位分享java直接选择排序的知识,其中也会对java中选择排序进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

JAVA中有哪几种常用的排序方法?

最主要的是冒泡排序、选择排序、插入排序以及快速排序

1、冒泡排序

冒泡排序是一个比较简单的排序方法。在待排序的数列基本有序的情况下排序速度较快。若要排序的数有n个,则需要n-1轮排序,第j轮排序中,从第一个数开始,相邻两数比较,若不符合所要求的顺序,则交换两者的位置;直到第n+1-j个数为止,第一个数与第二个数比较,第二个数与第三个数比较,......,第n-j个与第n+1-j个比较,共比较n-1次。此时第n+1-j个位置上的数已经按要求排好,所以不参加以后的比较和交换操作。

例如:第一轮排序:第一个数与第二个数进行比较,若不符合要求的顺序,则交换两者的位置,否则继续进行二个数与第三个数比较......。直到完成第n-1个数与第n个数的比较。此时第n个位置上的数已经按要求排好,它不参与以后的比较和交换操作;第二轮排序:第一个数与第二个数进行比较,......直到完成第n-2个数与第n-1个数的比较;......第n-1轮排序:第一个数与第二个数进行比较,若符合所要求的顺序,则结束冒泡法排序;若不符合要求的顺序,则交换两者的位置,然后结束冒泡法排序。

共n-1轮排序处理,第j轮进行n-j次比较和至多n-j次交换。

从以上排序过程可以看出,较大的数像气泡一样向上冒,而较小的数往下沉,故称冒泡法。

public void bubbleSort(int a[])

{

int n = a.length;

for(int i=0;in-1;i++)

{

for(int j=0;jn-i-1;j++)

{

if(a[j] a[j+1])

{

int temp = a[j];

a[j] = a[j + 1];

a[j + 1] = temp;

}

}

}

}

2、选择排序

选择法的原理是先将第一个数与后面的每一个数依次比较,不断将将小的赋给第一个数,从而找出最小的,然后第二个数与后面的每一个数依次比较,从而找出第二小的,然后第三个数与后面的每一个数依次比较,从而找出第三小的.....直到找到最后一个数。

public void sort(int x[])

{

int n=x.length;

int k,t;

for(int i=0;in-1;i++)

{

k=i;

for(int j=i+1;j=n;j++)

{

if(x[j]x[k])k=j;

if(k!=i)

{

t=x[i];

x[i]=x[k];

x[k]=t;

}

}

}

}

3、插入排序

插入排序的原理是对数组中的第i个元素,认为它前面的i-1个已经排序好,然后将它插入到前面的i-1个元素中。插入排序对少量元素的排序较为有效.

public void sort(int obj[])

{

for(int j=1;jobj.length;j++)

{

int key=obj[j];

int i=j-1;

while(i=0obj[i]key)

{

obj[i+1]=obj[i];

i--;

}

obj[i+1]=key;

}

}

4、快速排序

快速排序是对冒泡排序的一种改进。它的基本思想是:通过一次排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按次方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此大道整个数据变成有序序列。

public void quickSort(int obj[],int low,int high)

{

int i=low;

int j=high;

int keyValue=obj[i];

while(ij)

{

int temp=0;

while(ijobj[j]=keyValue)

{

j=j-1;

}

temp=obj[j];

obj[j]=obj[i];

obj[i]=temp;

while(ijobj[i]=keyValue)

{

i=i+1;

}

temp=obj[j];

obj[j]=ojb[i];

obj[i]=temp;

}

obj[i]=keyValue;

if(lowi-1)

{

quickSort(obj,low,i-1);

}

if(highi+1)

{

quickSort(obj,i+1,high);

}

}

java直接选择排序

我写的自己对吧,第二个循环的开始结束位置问题

import java.util.Arrays;

import java.util.Random;

public class CheckSort {

    public static void main(String[] args) {

        Random r = new Random();

        int size = 10;

        int arr[] = new int[size];

        for (int i = 0; i  size; i++) {

            arr[i] = r.nextInt(100);

        }

        System.out.println(Arrays.toString(arr));

        sort(arr);

        System.out.println(Arrays.toString(arr));

    }

    public static void sort(int[] arr) {

        for (int i = 0; i  arr.length-1; i++) {

            int min = arr[i];

            int index = i;

            for (int j = i + 1; j  arr.length; j++) {

                if (arr[j]  min) {

                    min = arr[j];

                    index = j;

                }

            }

            if (i != index) {

                int temp = arr[i];

                arr[i] = min;

                arr[index] = temp;

            }

        }

    }

}

直接选择排序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 = ; i splitedNumbers length; i++) {

if (splitedNumbers[i] trim() length() != ) {

try {

numList add(index++ Double 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 = ; i numList size(); i++)

if (i != numList size() )

resString = resString + numList get(i) + ;

else

// If be the last string

resString = resString + numList 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 = ; j numList size() ; j++) {

minPosition = j;

for (int i = j + ; i numList 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怎么让数组的数字从大到小排序?

将数字从大到小排序的方法:

例如简一点的冒泡排序,将第一个数字和后面的数字逐个比较大小,如果小于,则互换位置,大于则不动。此时,第一个数为数组中的最大数。然后再将第二个数与后面的数逐个比较,以次类推。

示例代码如下: 

public class Test { 

public static void main(String[] args) { 

int [] array = {12,3,1254,235,435,236,25,34,23}; 

int temp; 

for (int i = 0; i  array.length; i++) { 

for (int j = i+1; j  array.length; j++) { 

if (array[i]  array[j]) { 

temp = array[i]; 

array[i] = array[j]; 

array[j] = temp; // 两个数交换位置 

for (int i = 0; i  array.length; i++) { 

System.out.print(array[i]+"  "); 

}

数组对于每一门编程语言来说都是重要的数据结构之一,当然不同语言对数组的实现及处理也不尽相同。

Java 语言中提供的数组是用来存储固定大小的同类型元素。

你可以声明一个数组变量,如 numbers[100] 来代替直接声明 100 个独立变量 number0,number1,....,number99

扩展资料

Java中利用数组进行数字排序一般有4种方法:

1、选择排序是先将数组中的第一个数作为最大或最小数,然后通过循环比较交换最大数或最小数与一轮比较中第一个数位置进行排序。

2、冒泡排序也是先将数组中的第一个数作为最大或最小数,循环比较相邻两个数的大小,满足条件就互换位置,将最大数或最小数沉底。

3、快速排序法主要是运用Arrays类中的Arrays.sort方法()实现。

4、插入排序是选择一个数组中的数据,通过不断的插入比较最后进行排序。

怎么理解JAVA的直接选择排序法

很小的错误,看下注释的地方

public class Outfile {

public static void main(String[] args) {

int a[] = { 20, 29, 21, 45, 68, 15, 3, 5 };

for (int i = 0; i a.length - 1; i++) {

int min = i;

for (int j = i + 1; j a.length; j++) {

if (a[j] a[min]) {

min = j;

}

}

if (min != i) {//这一段从上面内层的for拿了出来

int b = a[min];

a[min] = a[i];

a[i] = b;

}

}

for (int c = 0; c a.length; c++) {

System.out.println(a[c]);

}

}

}

java直接选择排序出错

您应该将这三句代码放到if代码块中,即可得到从的到小的排序。

int temp = arr[arr.length-i];

arr[arr.length-i] = arr[index];

arr[index] = temp;

完整代码为

public class ChoiceSort {

public static void main(String[] args) {

int arr[] = {64,1,75,46,7};

int index;

for(int i=1; i  arr.length; i++){

index = 0;

for(int j = 1; j=arr.length-1; j++) {

if(arr[index]arr[j]) {

index = j;

int temp = arr[arr.length-i];

arr[arr.length-i] = arr[index];

arr[index] = temp;

}

}

}

for(int tmp : arr){

System.out.print(tmp + ",");

}

}

}

java直接选择排序的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java中选择排序、java直接选择排序的信息别忘了在本站进行查找喔。