---
# System prepended metadata

title: 資料結構 20221212_Sorting
tags: [java, Data Structure]

---

# 資料結構 20221212_Sorting

>撰寫人[name=AmiYaku1049] [首頁--天空路1049號](https://skys-kid-lai.github.io/1004/)
>>最後編輯[time=Wed, Jan 18, 2023 8:17 PM]
___
## 題目敘述
- 測資：課本第8-56頁第8題，11, 8, 14, 7, 6, 8', 23, 4 

- 排序 
1.氣泡法
2.選擇法
3.插入法

- 輸出內容
1.第N回排序結果
2.比較次數
3.交換次數
## 程式碼
```java=
class ClassWork_1110832059_1212_Sorting extends Object
{
	int data[] = new int[]{11,8,14,7,6,8,23,4};
	int bdata[] = new int[]{11,8,14,7,6,8,23,4};
	int sdata[] = new int[]{11,8,14,7,6,8,23,4};
	int idata[] = new int[]{11,8,14,7,6,8,23,4};

	public static void main(String[] args) 
	{
		ClassWork_1110832059_1212_Sorting point = new ClassWork_1110832059_1212_Sorting();

		System.out.println("----------原始資料----------");
		point.ShowArr();

		System.out.println("\n----------氣泡排序----------");
		point.ShowBubble();

		System.out.println("\n----------選擇排序----------");
		point.ShowSelect();

		System.out.println("\n----------插入排序----------");
		point.ShowInsert();
	}

	public void ShowArr()
	{
		for (int i = 0;i < data.length ;i++ )
		{
			System.out.print(data[i] + " ");
		}
		System.out.println();
	}

	public void ShowBubble()
	{
		int compare = 0, change = 0, i, j, tmp;
		for (i = bdata.length-1; i >= 0 ; i-- )
		{
			for (j = 0; j < i; j++ )
			{
				if(bdata[j+1] < bdata[j])
				{
					tmp = bdata[j];
					bdata[j] = bdata[j+1];
					bdata[j+1] = tmp;
					change ++;
					compare ++;
				}
				else
					compare ++;
			}
			
			System.out.print("第" + (bdata.length-i) + "次排序後的結果：");
			for (j = 0; j < bdata.length ; j++ )
			{
				System.out.print(bdata[j] + " ");
			}
			System.out.println();
		}

		System.out.println("\n比較次數：" + compare + "             交換次數：" + change);
	}

	public void ShowSelect()
	{
		int compare = 0, change = 0, tmp,i,j;
		for (i = 0; i < sdata.length -1; i++)
		{
			for (j = i+1; j < sdata.length; j++)
			{
				if(sdata[j] < sdata[i])
				{
					tmp = sdata[i];
					sdata[i] = sdata[j];
					sdata[j] = tmp;
					change ++;
					compare ++;
				}
				else
					compare ++;
			}
			System.out.print("第" + (i+1) + "次排序後的結果：");
			for (j = 0; j < sdata.length ; j++ )
			{
				System.out.print(sdata[j] + " ");
			}
			System.out.println();
		}
		System.out.println("\n比較次數：" + compare + "             交換次數：" + change);
	}

	public void ShowInsert()
	{
		int compare = 0, change = 0, tmp, i, j, k;
		for (i = 1; i < idata.length; i++)
		{
			tmp = idata[i];
			j = i -1;
			
			while(j >= 0 && tmp < idata[j])
			{
				idata[j+1] = idata[j];
				j--;
				compare++;
			}
			change++;
			idata[j+1] = tmp;
			System.out.print("第" + i + "次排序後的結果：");
			for(k = 0; k <idata.length; k ++)
			{
				System.out.print(idata[k] + " ");
			}
			System.out.println();
		}
		System.out.println("\n如果第二小於第一元素的次數：" + compare + "\n將最小的元素向前放的次數：" + change);
	}
}
```

## 結果圖示
![](https://i.imgur.com/9LMRl5g.png =50%x)

## 用書資訊
>書名：圖解資料結構 使用java（第三版）
>作者：吳燦銘、胡昭民
>出版社：博碩文化
>出版年份：2018年05月