iT邦幫忙

1

程式Java

  • 分享至 

  • xImage

1.排序與搜尋
a. 隨機產生 10 個介於 0 ~ 99 之整數。
b. 以選擇排序演算法,根據由小到大的方式陪序後輸出。 c. 輸入一個整數 x,以二分搜尋的方式,輸出其出現的位置,或是未出現。

看更多先前的討論...收起先前的討論...
Luis-Chen iT邦新手 4 級 ‧ 2018-01-12 16:17:22 檢舉
報告老師!! @朱雯雅 今天請假沒來
報價,外面解題,每題三千,需要傳報價單嘛
學校作業 請自行處理
@_@
小魚 iT邦大師 1 級 ‧ 2018-01-13 12:20:23 檢舉
這題的話,3000是可以啦
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2018-01-16 09:45:57

主程式 用這個
把原本其中寫固定的數字陣列
改成用亂數產生
然後再用選擇排序即可

0
aiden
iT邦新手 5 級 ‧ 2018-01-18 15:50:20

開啟eclipse -> 建立新專案 -> 專案點右鍵後 新增一個java檔案
->檔案名稱命名為 seohyun.java -> 複製貼上下方程式碼 -> build
p.s. 如eclipse開不起來請先裝Java JDK, 一些安裝版本或不知道怎麼build按哪裡等眉角問題可以再問

程式碼

import java.util.Scanner;

public class seohyun {
	//這是二元搜尋
    public static int binarySearch(int[] list,int item) {
        int left = 0, right = list.length;
        while(left<=right) {
            int mid = (left + right)/2;
            if(list[mid]==item)
                return mid;
            else {
                if(list[mid]>item) {
                    right = mid -1;
                } else {
                    left = mid +1;
                }
            }
        }
        return -1;
    }	
	//這是選擇排序
	public static void selectionSort(int[] list) {
		int i, j, min, temp, len = list.length;
		for ( i = 0; i < len - 1; i++ ) {
			min = i;
			for ( j = i + 1; j < len; j++ )
				if ( list[min] > list[j] ) {
					min = j;
				}
			temp = list[min]; 
			list[min] = list[i];
			list[i] = temp;
		}
	}	
	//這是main方法
    public static void main(String args[]) {		
        Scanner input = new Scanner(System.in);
		System.out.print("\na. 隨機產生 10 個介於 0 ~ 99 之整數。\n");
		int[] list;
		list = new int[10];
		for( int i = 0 ; i < list.length ; i++ ) {
            list[i] = (int)(Math.random() * 99 + 1 );
			System.out.print(list[i] + " " );
        }		
		System.out.print("\n\nb. 以選擇排序演算法,根據由小到大的方式陪序後輸出。\n");
		selectionSort(list);
		for ( int i = 0 ; i < list.length ; i++ ) { 
			System.out.print(list[i] + " " ); 
		}    
        System.out.print("\n\nc. 輸入一個整數 x,以二分搜尋的方式,輸出其出現的位置,或是未出現。 :\n請輸入要查詢數:");
		int searchkey = input.nextInt();		
        int ans =  binarySearch( list , searchkey );			
        if( ans > -1 ) {
            System.out.println("\n找到資料! 索引位置在: " + ans );
        } else
            System.out.println("\n找不到資料!");
	}
}

執行結果

失敗未出現
https://ithelp.ithome.com.tw/upload/images/20180118/201080641Cn5sHxq2V.png

成功找到位置
https://ithelp.ithome.com.tw/upload/images/20180118/20108064VUtlz2Ioqc.png

用別人的東西拼拼湊湊
沒抽離也沒分離
try catch也沒做
會有bug
但要求的正常輸入沒問題
僅供提供個架構方向參考

我要發表回答

立即登入回答