夢想飛翔

          自強不息
          posts - 111, comments - 30, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          三種常見java算法

          Posted on 2007-02-04 23:07 love1563 閱讀(350) 評論(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++;
          }

          }

          }


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 项城市| 昔阳县| 定南县| 北宁市| 武汉市| 成武县| 西盟| 东方市| 鄂托克前旗| 宁河县| 宝丰县| 东乡族自治县| 仁布县| 临夏市| 普陀区| 丰城市| 黑龙江省| 新蔡县| 齐河县| 商城县| 十堰市| 东乌珠穆沁旗| 宜兰市| 湾仔区| 阜康市| 昭苏县| 改则县| 南川市| 双辽市| 扎赉特旗| 北辰区| 济宁市| 巴林右旗| 理塘县| 上栗县| 留坝县| 环江| 庆安县| 延津县| 周至县| 温泉县|