gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
c++ 排序方法 代码
- User
c++ 排序方法 代码
- Assistant
以下是一些常见的C++排序方法的示例代码:
- 冒泡排序
void bubbleSort(int arr[], int n) { for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }- 插入排序
void insertionSort(int arr[], int n) { for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } }- 选择排序
void selectionSort(int arr[], int n) { for (int i = 0; i < n-1; i++) { int minIdx = i; for (int j = i+1; j < n; j++) { if (arr[j] < arr[minIdx]) { minIdx = j; } } if (minIdx != i) { int temp = arr[i]; arr[i] = arr[minIdx]; arr[minIdx] = temp; } } }- 快速排序
int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j <= high-1; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi-1); quickSort(arr, pi+1, high); } }这些都是常见的排序算法,可以根据自己的需要选择其中一个来排序一个整数数组。
- User
c++ sizeof 函数
- Assistant
C++中
sizeof是一个运算符,用于获取一个类型或变量的大小(以字节为单位)。sizeof函数可以用于任何数据类型。用法示例:
int main() { int num = 10; cout << "Size of int: " << sizeof(int) << " bytes" << endl; cout << "Size of num: " << sizeof(num) << " bytes" << endl; double arr[] = { 1.0, 2.0, 3.0, 4.0, 5.0 }; int size = sizeof(arr) / sizeof(arr[0]); cout << "Size of arr[]: " << sizeof(arr) << " bytes" << endl; cout << "Number of elements in arr[]: " << size << endl; return 0; }输出:
Size of int: 4 bytes Size of num: 4 bytes Size of arr[]: 40 bytes Number of elements in arr[]: 5在上面的示例中,
sizeof函数用于获取int类型和num变量的大小,并输出结果。然后,sizeof函数也被用来计算数组arr的大小(以字节为单位),并通过将其除以单个元素的大小来计算出数组中的元素数。注意,sizeof函数返回的是size_t类型的无符号整数值。请注意,
sizeof计算的结果是在编译时确定的,因此它可以用于静态地获取类型或变量的大小。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.