1. 程式人生 > >用Scala語言實現氣泡排序

用Scala語言實現氣泡排序

Java語言氣泡排序:

/*
 * 氣泡排序
 */
public class BubbleSort {
  public static void main(String[] args) {
    int[] arr={1,4,2,-4,6,22,8,-9,-88,0,56,437,97,-356,666,-8};
    System.out.println("排序前陣列為:");
    for(int num:arr){
      System.out.print(num+" ");
    }
    for(int i=0;i<arr.length-1;i++){//外層迴圈控制排序趟數
      for(int j=0;j<arr.length-1-i;j++){//內層迴圈控制每一趟排序多少次
        if(arr[j]>arr[j+1]){
          int temp=arr[j];
          arr[j]=arr[j+1];
          arr[j+1]=temp;
        }
      }
    } 
    System.out.println();
    System.out.println("排序後的陣列為:");
     for(int num:arr){
       System.out.print(num+" ");
     } 
  }
 }


Scala語言實現氣泡排序:

package com.szd.day03

import scala.collection.mutable.ArrayBuffer

/**
  * 氣泡排序
  */
object BubbleSort {
  def main(args: Array[String]): Unit = {
    val arr = Array( 1,4,2,-4,6,22,8,-9,-88,0,56,437,97,-356,666,-8)
    var temp=0
    for (i <- 1 until arr.length){
      for(j <- 0 until (arr.length-1)){
        if (arr(j) < arr(j+1)){
          temp = arr(j)
          arr(j)=arr(j+1)
          arr(j+1)=temp
        }
      }
    }
    print(arr.mkString(","))
  }
}