改明白了

This commit is contained in:
iridiumR 2021-10-15 15:20:32 +08:00
parent 9003a33ecd
commit 7857549051
3 changed files with 54 additions and 13 deletions

View file

@ -13,8 +13,9 @@ int main()
Vec v(len); Vec v(len);
v.printall(); v.printall();
system("pause"); system("pause");
printf("排序\n"); printf("排序:秩为%d\n",v.getused());
v.sort(); // v.bubbleSort();
v.mergeSort(0,v.getused());
v.printall(); v.printall();
while (1) while (1)
{ {
@ -26,7 +27,7 @@ int main()
case 1: case 1:
printf("输入待插入数值\n"); printf("输入待插入数值\n");
scanf("%d", &temp[0]); scanf("%d", &temp[0]);
(v.insert(v.search(temp[0]), temp[0]) != -1) ? (printf("输出数组\n")) : (printf("无此元素或超出范围\n")); (v.insert(v.search(temp[0]) + 1, temp[0]) != -1) ? (printf("输出数组\n")) : (printf("无此元素或超出范围\n"));
v.printall(); v.printall();
break; break;

View file

@ -62,6 +62,12 @@ void Vec::shrink()
//λÖà ÊýÖµ //λÖà ÊýÖµ
int Vec::insert(int locate, int value) int Vec::insert(int locate, int value)
{ {
if (locate == _used + 1)
{
_used++;
_v[_used] = value;
return 0;
}
if (locate < 0 || locate > _used) if (locate < 0 || locate > _used)
return -1; return -1;
@ -151,11 +157,11 @@ int Vec::getused()
void Vec::printall() void Vec::printall()
{ {
for (int i = 0; i < _used; i++) for (int i = 0; i <= _used; i++)
printf("%d\n", _v[i]); printf("%d\n", _v[i]);
} }
void Vec::sort() void Vec::bubbleSort()
{ {
int n = _used; int n = _used;
bool sorted = false; bool sorted = false;
@ -164,7 +170,7 @@ void Vec::sort()
{ {
sorted = true; sorted = true;
for (int i = 1; i < n; i++) for (int i = 1; i <= n; i++)
{ {
if (_v[i - 1] > _v[i]) if (_v[i - 1] > _v[i])
{ {
@ -178,6 +184,17 @@ void Vec::sort()
_sorted = true; _sorted = true;
} }
void Vec::mergeSort(int lo, int hi)
{
if (lo >= hi)
{
return;
}
int mi = lo + (hi - lo) / 2;
mergeSort(lo, mi);
mergeSort(mi + 1, hi);
merge(lo, mi, hi);
}
int Vec::search(int e) int Vec::search(int e)
{ {
if (_sorted == false) if (_sorted == false)
@ -189,3 +206,24 @@ int Vec::search(int e)
return i - 1; return i - 1;
} }
void Vec::merge(int lo, int mi, int hi)
{
int i = lo, j = mi + 1, k = 0;
int *temp = new int[hi - lo + 1];
while (i <= mi && j <= hi)
{
if (_v[i] <= _v[j])
temp[k++] = _v[i++];
else
temp[k++] = _v[j++];
}
while (i <= mi)
temp[k++] = _v[i++];
while (j <= hi)
temp[k++] = _v[j++];
for (i = lo, k = 0; i <= hi; i++, k++)
_v[i] = temp[k];
delete[] temp;
}

View file

@ -39,7 +39,7 @@ public:
int find(int value); int find(int value);
void sort(); void bubbleSort();
void printall(); void printall();
@ -48,7 +48,9 @@ public:
int getused(); int getused();
int count(int value); int count(int value);
void mergeSort(int lo, int hi);
private:
void merge(int lo, int mi, int hi);
}; };