歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java實現直接插入排序

Java實現直接插入排序

日期:2017/3/1 10:13:50   编辑:Linux編程

Java直接插入排序是有一個已經有序的數據序列,要求在這個已經排好的數據序列中插入一個數,但要求插入後此數據序列仍然有序;排序的主要思想是:將有序數存放在數組a中,要插入的數為x,首先要確定x在數組a中的位置p,然後將數組a中p位置以後的數都往後移動一位,空出a(p),然後將x放入a(p)位置,這樣即可實現插完以後的數據仍然有序。

首先生成一組隨機數:

  1. protected void do_button_actionPerformed(ActionEvent e)
  2. {
  3. Random random = new Random();
  4. textArea1.setText("");
  5. for(int i = 0;i<array.length; i++){
  6. array[i] = random.nextInt(90);
  7. textArea.append(array[i] + "\n");
  8. }
  9. }

排序算法代碼:

  1. protected void do_button1_actionPerformed(ActonEvent e)
  2. {
  3. int tmp;
  4. int j;
  5. for(int i = 1;i<array.length; i++)
  6. {
  7. tmp = array[i];
  8. for(j =i - 1; j>=0 && array[j] > tmp; j--){
  9. array[j+1] = tmp;
  10. }
  11. array[j+1] = tmp;
  12. }
  13. textArea2.setText("");
  14. for(int i = 0;i<array.length; i++){
  15. textArea2.append(array[i] + "\n");
  16. }
  17. }

 
各種排序算法的比較請見 http://www.linuxidc.com/Linux/2012-02/55383.htm
Copyright © Linux教程網 All Rights Reserved