Dobrý den, potřeboval bych poradit s algoritmizací. Program by mi měl vyhledat 3. největší hodnotu z libovolného dvourozměrného pole. Napadla mě možnost se sortem, ale potřeboval bych to udělat bez něj. Jedná se o jazyk C++. Děkuji za případné rady.
Fórum › C / C++
3. největší hodnota v poli

pouziva se vicemene select sort... kdy ho projedes jen tolikrat, kolikatou hodnotu potrebujes... (nebudes radit vse kdyz nemusis)
pripadne se da i udelat objekt, kterymu se zada pocet polozek a on se postara o vlozeni na spravne misto (zalezi na tom jestli c++ nebo jen C)
Btw pokud chceš nějaký vlastní řešení, tak jsem se pokusil udělat něco, kde není žádnej sort, jen vyhledá 3 největší a ty seřadí :) nevim jestli je to rychlejší než select sort (nezkousel jsem)
#include <iostream>
#include <time.h>
struct Find3Max
{
public:
Find3Max(int* arr, const int length, int*& result)
{
if (!arr) return;
result = new int[3];
for (int i = 0; i < length; ++i)
{
if (*(arr + i) > *(result + 2))
{
if (!existsValue(result, 3, *(arr + i)))
{
*(result + 2) = *(result + 1);
*(result + 1) = *result;
*result = *(arr + i);
sort3(result);
}
}
}
}
private:
void swap(int& a, int& b) {
int tmp = a;
a = b;
b = tmp;
}
bool existsValue(int* arr, const int length, const int value) const {
for (int i = 0; i < length; ++i)
if (*(arr + i) == value) return true;
return false;
}
void sort3(int* arr) {
if (*arr < *(arr + 1)) swap(*arr, *(arr + 1));
if (*(arr + 1) < *(arr + 2)) swap(*(arr + 1), *(arr + 2));
if (*arr < *(arr + 1)) swap(*arr, *(arr + 1));
}
};
int main ()
{
srand((unsigned int) time(0));
const int LENGTH = 10;
int arr[LENGTH];
for (int i = 0; i < LENGTH; ++i) {
*(arr + i) = rand() % 100;
}
int* result = 0;
Find3Max(arr, LENGTH, result);
for (int i = 0; i < 3; ++i)
std::cout << *(result + i) << ", ";
return EXIT_SUCCESS;
}
Děkuji moc, oba příspěvky velice pomohli. :)

Přidej příspěvek
Toto téma je starší jak čtvrt roku – přidej svůj příspěvek jen tehdy, máš-li k tématu opravdu co říct!
Ano, opravdu chci reagovat → zobrazí formulář pro přidání příspěvku
×Vložení zdrojáku
×Vložení obrázku
×Vložení videa
Aktuálně jsou podporována videa ze serverů YouTube, Vimeo a Dailymotion.
×






























































Uživatelé prohlížející si toto vlákno
Uživatelé on-line: 0 registrovaných, 5 hostů
Podobná vlákna
Největší v poli polí — založil Noneus
Počet nejmenších opakujících se prvků v poli a jejich hodnota — založil K4BlOs
3 největší číslo — založil d
Největší společný dělitel — založil Blujacker
Největší společný dělitel — založil Dave
Moderátoři diskuze