在输入随机5个整数,进行从小到大的排序,但是输出的值是乱码
#include <iostream>
constexpr auto N = 5;
using namespace std;
void insert_sort(int a[], int n) //直接插入排序
{
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = a[i];
j = i - 1;
while (j >= 0 && temp < a[j])
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
int main()
{
int* pArray;
int i;
pArray = new int[N]; //动态分配数组
//向数组中输入5个整数
insert_sort(pArray);
for (i = 0; i < N; i++)
cin >> pArray[i];
cout << pArray[i] << " ";
system("pause");
return 0;
}
似乎无法调用函数 insert_sort
使随机输入的5个整数从小到大排序
冒泡排序就行了
你的函数有两个参数啊
#include <iostream>
constexpr auto N = 5;
using namespace std;
void insert_sort(int a[], int n) //直接插入排序
{
int i, j, temp;
for (i = 0; i < n-1; i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}
int main()
{
int* pArray;
int i;
pArray = new int[N]; //动态分配数组
//向数组中输入5个整数
for (i = 0; i < N; i++)
cin >> pArray[i];
insert_sort(pArray,N);
for(i=0;i<N;i++)
cout << pArray[i] << " ";
system("pause");
return 0;
}
#include <iostream>
void swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void sort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (a[j] > a[j + 1])
swap(a[j], a[j + 1]);
}
int main()
{
const int N = 5;
int a[N];
for (int i = 0; i < N; i++)
std::cin >> a[i];
sort(a, N);
for (int i = 0; i < N; i++)
std::cout << a[i] << ' ';
std::cout << std::endl;
return 0;
}