标签:sof main void clu str 方法 out IV sort
图解:
方法一代码:
1 #include <iostream> 2 using namespace std; 3 4 void insertSort_1(int arr[], int length) 5 { 6 int j, key; 7 for (int i = 1; i < length; i++) 8 { 9 key = arr[i]; 10 j = i - 1; 11 while (j >= 0 && arr[j] > key) 12 { 13 arr[j + 1] = arr[j]; 14 j--; 15 } 16 arr[j + 1] = key; 17 } 18 } 19 20 int main() 21 { 22 int iArr[] = { 7, 8, 9, 5, 2, 0, 12, 6 }; 23 int len = sizeof iArr / sizeof(iArr[0]); 24 25 cout << "排序前:"; 26 for (int i = 0; i < len; i++) 27 cout << iArr[i] << " "; 28 cout << endl; 29 30 cout << "\n排序后:"; 31 insertSort_1(iArr, len); 32 for (int j = 0; j < len; j++) 33 cout << iArr[j] << " "; 34 cout << endl; 35 return 0; 36 }
输出结果:
方法二代码:
1 #include <iostream> 2 using namespace std; 3 4 void insertSort_0(int arr[], int length) 5 { 6 int i, j, key; 7 for (i = 0; i < length; i++) 8 { 9 key = arr[i]; 10 for (j = i - 1; j >= 0; j--) 11 { 12 if (arr[j] > key) 13 arr[j + 1] = arr[j]; 14 else 15 break; 16 } 17 arr[j + 1] = key; 18 } 19 } 20 21 int main() 22 { 23 int iArr[] = { 7, 8, 9, 5, 2, 0, 12, 6 }; 24 int len = sizeof iArr / sizeof(iArr[0]); 25 26 cout << "排序前:"; 27 for (int i = 0; i < len; i++) 28 cout << iArr[i] << " "; 29 cout << endl; 30 31 cout << "\n排序后:"; 32 insertSort_0(iArr, len); 33 for (int j = 0; j < len; j++) 34 cout << iArr[j] << " "; 35 cout << endl; 36 return 0; 37 }
输出结果:
标签:sof main void clu str 方法 out IV sort
原文地址:https://www.cnblogs.com/sunbines/p/9141378.html